package com.datatraffic.salesup;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.echo.holographlibrary.Bar;
import com.echo.holographlibrary.BarGraph;
import com.echo.holographlibrary.PieGraph;
import com.echo.holographlibrary.PieSlice;
import com.google.android.gms.internal.ac;
import com.google.android.gms.plus.model.people.Person.Cover;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.commonsware.cwac.locpoll.LocationPoller;
import com.commonsware.cwac.locpoll.LocationPollerParameter;
import com.datatraffic.broadcastservices.LocationReceiver;
import com.datatraffic.broadcastservices.ServicioAlarma;
import com.datatraffic.databasecontrol.DBHelper;
import com.datatraffic.databasecontrol.DatabaseControl;
import com.datatraffic.salesup.anim.ActivityTransitionAnimation;
import com.datatraffic.salesup.model.Form;
import com.datatraffic.salesup.model.Notificacion;
import com.datatraffic.salesup.model.Task;
import com.datatraffic.salesup.model.menu_prospectos;
import com.datatraffic.services.ManagerExecutor;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnClosedListener;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;


public class MenuActivity extends Activity implements OnClickListener,ConsumidorServicios{
	
	Button MapButton;
	Button MapPersuitButton;
	Button ImageButton;
	Button ButtonList;
	Button VideoButton;
	ImageView bla,logoMap;
	//EditText estPlace;
	Button syncButton;
	Button importButton;
	Button googleMapButton;
	Button tareasButton;
	Button btnActualizar;
	Button tareasButtonGuarda;
	ImageView btnhacer;
	DBHelper dbHelper;
	DatabaseControl dbcontrol;
	String filtro = "";
	
	EditText BuscarNombre;
	
	boolean e = false;
	private static final int OPTION_MENU_BACK =1;
	private static final int OPTION_MENU_EXIT =2;

	private int mCaller;
	public static final int CALLER_CARDEDITOR = 8;
	public static final int CALLER_CARDEDITOR_INTENT_ADD = 9;
	public static final int CALLER_INDICLASH = 10;

	public static final int CALLER_BIGWIDGET_EDIT = 4;
	public static final int CALLER_BIGWIDGET_ADD = 5;
	private static final int TIME_DIALOG_ID = 999, DATE_DIALOG_ID = 0;


	private static final String TAG = "Servicio Info";
	private Timer timerSync;
	private LocationManager locationManager;
	private LocationListener locationListener;
	private String latitud="0",longitud="0";
	private int syncTask=300000;

	
	private EditText nombre;
	private EditText apellido;
	private EditText documento;
	private EditText numeroTelefonico2;
	private EditText numeroCelular1;
	private EditText mensajeProximoContacto;
	private EditText observaciones;
	private TextView fechaderegistro;
	private TextView lblAvisoLegal;
	private LinearLayout lyAvisoLegal;
	private EditText numeroCelular2;
	private EditText numeroTelefonico1;
	private Spinner operadorActualdeTelevision;
	private Spinner Cobertura;
	private Spinner ProductoInteres;
	private Spinner tipodeContactoaRealizar;
	private String estadoR="CREADO";
	private Spinner Estado;
	private Spinner tipoDocumento;
	private Button timePicker;
	private Button datePicker;
	private Calendar cal;
	private int year;
	private int month;
	private int day;
	private int hour;
	private int minute;
	//private AutoCompleteTextView buscar;
	private Button submit;
	private ArrayList<String> strings;
	private ArrayList<String> strings2;
	private ArrayList<String> strings5;
	private ArrayList<String> strings4;
	private ArrayList<String> strings6;
	private ArrayList<String> strings7;

	
	private static boolean mChanged = false,isBack=false;//isForm=false,isStadis=false;
	private ImageView logo;
	private Button search; 
	private Location lastlocation;
	
	private BarGraph perDay, perHour;
	private SharedPreferences prefs;
	private String dateStart = "", dateEnd = "", dateHour = "",dateactual = "";
	private Button date1, date2, date3, filter1, filter2;
	private static final int DATE_1_ID = 1, DATE_2_ID = 2, DATE_3_ID = 3,DATE_4_ID = 4;
	private SlidingMenu menu,menu1;
	private String modo="";
	private String date4;
	private String tipoDocumentoR="";
	private String contactoaRealizarR="";
	private String operadorR="";
	private String coberturaR="";
	private String productointeresR="";
	private StringBuilder hourFinal=new StringBuilder("");
	private Form form;
	private ProgressDialog pd;
	private EditText direccion, correo;
	
	LinearLayout mContent;
	signature mSignature;
	Button mClear, mGetSign, mCancel;
	public static String tempDir;
	public int count = 1;
	public String current = null ,cadTotal="",result="";
	private Bitmap mBitmap;
	View mView;

	private AlertDialog.Builder builder;
	private AlertDialog alertDialog ;
	private byte[] foto;

	private Search s;
	
	
	private boolean isListForm=false,reggister=false;
	private ListAdapter adapter;
	private ListAdapterTasks adapter1;
	private ListAdapterMenuProspectos adapter2;
	private int page=0;
	private int Totalpage=0;
	public int contador=0;
	private String resultCount="0";
	private int id=0;
	
	private AlertDialog.Builder builderNoti;
	private AlertDialog builderNotiDos;
	
	private String celularDos="";
	private String nombreDos="";
	private String fechaDos="";
	private CheckBox acepto;
	
	private int CAMERA_REQUEST_CUATRO = 1891,
			CAMERA_REQUEST_CINCO = 1892;
	private Bitmap photo1;
	private Bitmap photo2;
	private Notificacion notify;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        setContentView(R.layout.activity_menu);
       
        dbHelper = new DBHelper(MenuActivity.this);
        dbcontrol = new DatabaseControl(MenuActivity.this);
        
        
        importButton = (Button) findViewById(R.id.menu_btn_video);
        importButton.setOnClickListener(this);
        
        MapButton = (Button) findViewById(R.id.menu_btn_map);
        MapButton.setOnClickListener(this);
        
        prefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
        
        if(prefs.getString("notificacion", "").equalsIgnoreCase("ok"))
        {
        	Editor editor = prefs.edit();
    		editor.putString("notificacion","");
    		editor.commit();

			celularDos=prefs.getString("celular","");
    		fechaDos=prefs.getString("fecha","");
    		nombreDos=prefs.getString("nombre","");
    		Log.e("NOMBRE A COLOCAR", nombreDos);
        	runOnUiThread(new Runnable() {
        		public void run() {

        			LayoutInflater inflater = (LayoutInflater)MenuActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
        			View layout = inflater.inflate(R.layout.push,(ViewGroup) findViewById(R.id.layout));

        			TextView titulo=(TextView) layout.findViewById(R.id.title);
        			TextView text=(TextView) layout.findViewById(R.id.text);
        			text.setText("Proxima cita es: "+fechaDos+". Por favor comunicate al numero: "+celularDos+"Con el señor(a): "+nombreDos+" para confirmar.");
        			//set up button
        			titulo.setText("Atención");
        			Button button = (Button) layout.findViewById(R.id.buttonOKIS);
        			button.setOnClickListener(new View.OnClickListener() {
        				@Override
        				public void onClick(View v) {
        					builderNotiDos.cancel();

        				}
        			});
        			
        			Button buttonCall = (Button) layout.findViewById(R.id.ButtonLlamar);
        			buttonCall.setOnClickListener(new View.OnClickListener() {
        				@Override
        				public void onClick(View v) {
        					Intent callIntent = new Intent(Intent.ACTION_CALL);
        					callIntent.setData(Uri.parse("tel:"+celularDos));
        					startActivity(callIntent);

        				}
        			});


        			builderNoti = new AlertDialog.Builder(MenuActivity.this);
        			builderNoti.setView(layout);
        			builderNotiDos = builderNoti.create();
        			builderNotiDos.show();
        		}
        	});
        }
        
        JSONObject json=new JSONObject();
        try {
			json.put("function", "numForms");
			json.put("user", prefs.getString("idUsuario", ""));
	        ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
			executor.execute(json);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        cal = Calendar.getInstance();
		year = cal.get(Calendar.YEAR);
		month = cal.get(Calendar.MONTH);
		day = cal.get(Calendar.DAY_OF_MONTH);
		hour = cal.get(Calendar.HOUR_OF_DAY);
		minute = cal.get(Calendar.MINUTE);
     
        estadoR="CREADO";
       
        googleMapButton = (Button) findViewById(R.id.Button01);
        googleMapButton.setOnClickListener(this);
        
        ButtonList = (Button) findViewById(R.id.Button03);
        ButtonList.setOnClickListener(this);
        
        
        bla = (ImageView) findViewById(R.id.imageView2);
        bla.setOnClickListener(this);
        
        tareasButton = (Button) findViewById(R.id.Button02);
        tareasButton.setOnClickListener(this);
        
        tareasButtonGuarda = (Button) findViewById(R.id.ButtonGuarda);
        //tareasButtonGuarda.setOnClickListener(this);
        tareasButtonGuarda.setVisibility(View.INVISIBLE);
  
        timerSync=new Timer();
        this.actualizarPosicion();
        this.ejecutar();
        this.iniciarTracking();
        
        
      
    }
    
    @Override
    protected void onResume() {
        super.onResume(); 
        
        prefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
        
        if(prefs.getString("notificacion", "").equalsIgnoreCase("ok"))
        {
        	Editor editor = prefs.edit();
    		editor.putString("notificacion","");
    		editor.commit();

			celularDos=prefs.getString("celular","");
    		fechaDos=prefs.getString("fecha","");
    		nombreDos=prefs.getString("nombre","");
    		Log.e("NOMBRE A COLOCAR", nombreDos);
        	runOnUiThread(new Runnable() {
        		public void run() {

        			LayoutInflater inflater = (LayoutInflater)MenuActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
        			View layout = inflater.inflate(R.layout.push,(ViewGroup) findViewById(R.id.layout));

        			TextView titulo=(TextView) layout.findViewById(R.id.title);
        			TextView text=(TextView) layout.findViewById(R.id.text);
        			text.setText("Proxima cita es: "+fechaDos+". Por favor comunicate al numero: "+celularDos+" .Con el se�or(a): "+nombreDos+" para confirmar.");
        			//set up button
        			titulo.setText("Atención");
        			Button button = (Button) layout.findViewById(R.id.buttonOKIS);
        			button.setOnClickListener(new View.OnClickListener() {
        				@Override
        				public void onClick(View v) {
        					builderNotiDos.cancel();

        				}
        			});
        			
        			Button buttonCall = (Button) layout.findViewById(R.id.ButtonLlamar);
        			buttonCall.setOnClickListener(new View.OnClickListener() {
        				@Override
        				public void onClick(View v) {
        					Intent callIntent = new Intent(Intent.ACTION_CALL);
        					callIntent.setData(Uri.parse("tel:"+celularDos));
        					startActivity(callIntent);

        				}
        			});

        			builderNoti = new AlertDialog.Builder(MenuActivity.this);
        			builderNoti.setView(layout);
        			builderNotiDos = builderNoti.create();
        			builderNotiDos.show();
        		}
        	});
        }

        
       
    }
    
    @Override
    protected void onPause() {
        super.onPause(); 
        
        prefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
        
        if(prefs.getString("notificacion", "").equalsIgnoreCase("ok"))
        {
        	Editor editor = prefs.edit();
    		editor.putString("notificacion","");
    		editor.commit();

			celularDos=prefs.getString("celular","");
    		fechaDos=prefs.getString("fecha","");
    		nombreDos=prefs.getString("nombre","");
    		Log.e("NOMBRE A COLOCAR", nombreDos);
        	runOnUiThread(new Runnable() {
        		public void run() {

        			LayoutInflater inflater = (LayoutInflater)MenuActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
        			View layout = inflater.inflate(R.layout.push,(ViewGroup) findViewById(R.id.layout));

        			TextView titulo=(TextView) layout.findViewById(R.id.title);
        			TextView text=(TextView) layout.findViewById(R.id.text);
        			text.setText("Proxima cita es: "+fechaDos+". Por favor comunicate al numero: "+celularDos+". Con el se�or(a): "+nombreDos+" para confirmar.");
        			//set up button
        			titulo.setText("Atención");
        			Button button = (Button) layout.findViewById(R.id.buttonOKIS);
        			button.setOnClickListener(new View.OnClickListener() {
        				@Override
        				public void onClick(View v) {
        					builderNotiDos.cancel();

        				}
        			});
        			
        			Button buttonCall = (Button) layout.findViewById(R.id.ButtonLlamar);
        			buttonCall.setOnClickListener(new View.OnClickListener() {
        				@Override
        				public void onClick(View v) {
        					Intent callIntent = new Intent(Intent.ACTION_CALL);
        					callIntent.setData(Uri.parse("tel:"+celularDos));
        					startActivity(callIntent);

        				}
        			});

        			builderNoti = new AlertDialog.Builder(MenuActivity.this);
        			builderNoti.setView(layout);
        			builderNotiDos = builderNoti.create();
        			builderNotiDos.show();
        		}
        	});
        }

        
       
    }
    
    @Override
    protected void onStop() {
        super.onStop(); 
        
        prefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
        
        if(prefs.getString("notificacion", "").equalsIgnoreCase("ok"))
        {
        	Editor editor = prefs.edit();
    		editor.putString("notificacion","");
    		editor.commit();

			celularDos=prefs.getString("celular","");
    		fechaDos=prefs.getString("fecha","");
    		nombreDos=prefs.getString("nombre","");
    		Log.e("NOMBRE A COLOCAR", nombreDos);
        	runOnUiThread(new Runnable() {
        		public void run() {

        			LayoutInflater inflater = (LayoutInflater)MenuActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
        			View layout = inflater.inflate(R.layout.push,(ViewGroup) findViewById(R.id.layout));

        			TextView titulo=(TextView) layout.findViewById(R.id.title);
        			TextView text=(TextView) layout.findViewById(R.id.text);
        			text.setText("Proxima cita es: "+fechaDos+". Por favor comunicate al numero: "+celularDos+" . Con el se�or(a): "+nombreDos+" para confirmar.");
        			//set up button
        			titulo.setText("Atención");
        			Button button = (Button) layout.findViewById(R.id.buttonOKIS);
        			button.setOnClickListener(new View.OnClickListener() {
        				@Override
        				public void onClick(View v) {
        					builderNotiDos.cancel();

        				}
        			});
        			
        			Button buttonCall = (Button) layout.findViewById(R.id.ButtonLlamar);
        			buttonCall.setOnClickListener(new View.OnClickListener() {
        				@Override
        				public void onClick(View v) {
        					Intent callIntent = new Intent(Intent.ACTION_CALL);
        					callIntent.setData(Uri.parse("tel:"+celularDos));
        					startActivity(callIntent);

        				}
        			});

        			builderNoti = new AlertDialog.Builder(MenuActivity.this);
        			builderNoti.setView(layout);
        			builderNotiDos = builderNoti.create();
        			builderNotiDos.show();
        		}
        	});
        }

        
       
    }
    
    private void iniciarTracking()
    {
    	AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
    	Intent i = new Intent(this, LocationPoller.class);

    	Bundle bundle = new Bundle();
    	LocationPollerParameter parameter = new LocationPollerParameter(bundle);
    	parameter.setIntentToBroadcastOnCompletion(new Intent(this,
    	        LocationReceiver.class));
    	// try GPS and fall back to NETWORK_PROVIDER
    	parameter.setProviders(new String[] { LocationManager.GPS_PROVIDER,
    	        LocationManager.NETWORK_PROVIDER });
    	parameter.setTimeout(120000);
    	i.putExtras(bundle);

    	PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
    	alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
    	        SystemClock.elapsedRealtime(), 300000, pi);
    }
    
    @Override
   	public boolean onKeyUp(int keyCode, KeyEvent event) {
   		// TODO Auto-generated method stub
   		switch(keyCode){
   			case KeyEvent.KEYCODE_BACK:
   			
   		}
   		return super.onKeyDown(keyCode, event);
   	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.activity_menu, menu);
    	super.onCreateOptionsMenu(menu);
        //CreateMenu(menu);
        return true;
    }
    
    /*public static String removeAcento(String input) {
		String original = "��������������u�������������������";
		String ascii = "aaaeeeiiiooouuunAAAEEEIIIOOOUUUNcC";
		String output = "";
		if (!input.toLowerCase().toString().equals("")) {
			output = input;
			for (int i = 0; i < original.length(); i++)
				output = output.replace(original.charAt(i), ascii.charAt(i));
		} else {
			output = "";
		}
		return output;
	}*/
    
    public static String removeAcento(String input) {
        return input.replaceAll("[^A-Z@ .a-z0-9]", "");
    }

	@Override
	@Deprecated
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIME_DIALOG_ID:
			// set time picker as current time
			return new TimePickerDialog(this, timePickerListener, hour, minute,
					false);
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, datePickerListener, year, month,
					day);
			
		case DATE_1_ID:
			return new DatePickerDialog(this, datePickerListener1, year, month,
					day);
		case DATE_2_ID:
			return new DatePickerDialog(this, datePickerListener2, year, month,
					day);
		case DATE_3_ID:
			return new DatePickerDialog(this, datePickerListener3, year, month,
					day);
			
		case DATE_4_ID:
			return new DatePickerDialog(this, datePickerListener4, year, month,
					day);
		}
		return null;
	}
	
	private DatePickerDialog.OnDateSetListener datePickerListener1 = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			dateStart = selectedYear + "-" + pad((selectedMonth + 1)) + "-"
					+ pad(selectedDay);
			date1.setText(dateStart);
		}
	};

	private DatePickerDialog.OnDateSetListener datePickerListener2 = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			dateEnd = selectedYear + "-" + pad((selectedMonth + 1)) + "-"
					+ pad(selectedDay);
			date2.setText(dateEnd);
		}
	};

	private DatePickerDialog.OnDateSetListener datePickerListener3 = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			dateHour = selectedYear + "-" + pad((selectedMonth + 1)) + "-"
					+ pad(selectedDay);
			date3.setText(dateHour);
		}
	};
	
	

	private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {

		public void onTimeSet(TimePicker view, int selectedHour,
				int selectedMinute) {
			hour = selectedHour;
			minute = selectedMinute;
			hourFinal = new StringBuilder().append(pad(hour)).append(":")
					.append(pad(minute));
			timePicker.setText(hourFinal);
		}
	};

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	private String date="";
	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
		
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			date = selectedYear + "-" + (selectedMonth + 1) + "-" + selectedDay;
			datePicker.setText(date );
		}
	};
	
	private void addAdapterToViews() {
        /*buscar.setAdapter(new AutoCompleteAdapter(MenuActivity.this));
        buscar.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Log.i("Seleccionado",""+position);
				isListForm=false;
				modo="editando";
				ArrayList<Form> respuestas = s.getRespuesta();
				if(position<respuestas.size())
				{
				  form = respuestas.get(position);
				  fillForm(form);
				}
				else
				{
					Log.i("LONGITUD", String.valueOf(respuestas.size()));
				}
				
				
			}
		});*/
        
       /* buscar.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (buscar.isFocused())
					logo.setVisibility(View.GONE);
				else if (buscar.getText().toString().equalsIgnoreCase(""))
					logo.setVisibility(View.VISIBLE);
			}
		});*/
        
    }	
	
	
	private ListView  listaFormularios;
	private void logicUIListaFormularios()
    {
    	this.runOnUiThread(new Runnable() {
    		@Override
    		public void run() {
    			
    			filtro="";			
    			MenuActivity.this.setContentView(R.layout.lista_formularios);
    			prefs = PreferenceManager
    					.getDefaultSharedPreferences(getApplicationContext());
    			page=0;
    			
    			JSONObject request = new JSONObject();
				try {
					request.put("function", "listaform");
					request.put("mobile_key", "");
					request.put("resource", "");
					request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
					request.put("query", "");
					request.put("start", page);
					request.put("limit", 5);
					request.put("order", "");
					request.put("filtro",filtro);
					request.put("mode", "");
					Log.d("request", request.toString());

					pd = new ProgressDialog(MenuActivity.this);
					pd.setCancelable(false);
					pd.setMessage("Enviando información, por favor espere un momento!!!");
					pd.show();
					ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
					executor.execute(request);
				} catch (JSONException e) {
					Toast.makeText(getApplicationContext(),
							"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
					e.printStackTrace();
				}
				
				// sliding
				menu = new SlidingMenu(MenuActivity.this);
				menu.setMode(SlidingMenu.RIGHT);
				menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
				menu.setShadowWidthRes(R.dimen.shadow_width);
				menu.setShadowDrawable(R.drawable.shadowslidemenu);
				menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
				menu.setFadeEnabled(true);
				menu.setFadeDegree(0.35f);
				menu.setBackgroundResource(android.R.color.white);
				menu.attachToActivity(MenuActivity.this, SlidingMenu.SLIDING_CONTENT);
				menu.setOnClosedListener(new OnClosedListener() {

					@Override
					public void onClosed() {
						mostrarMenuPrincipal(null);
					}
				});
				
				
				
				btnhacer=(ImageView)findViewById(R.id.hacer);
				btnhacer.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						menu.showMenu();
						mostrarMenuPrincipal(null);
					}
				});
							

				btnActualizar=(Button)findViewById(R.id.btnActualizar);
				btnActualizar.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub   
						DetectordeInternet	objDetector = new DetectordeInternet(MenuActivity.this);
						if(objDetector.estasConectado()){
							    						

							JSONObject cargar=new JSONObject();
							try {
								cargar.put("function", "sincronizar");
								sincronizar(cargar);
								ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
								executor.execute(cargar);
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();							
							}

							if(VariablesdeSesion.getInstance().getContadorFormularios().equals("0"))
							{
								//Toast.makeText(getApplicationContext(), "Cargando Lista de Servicios", Toast.LENGTH_SHORT).show();
								dbHelper.Eliminar();	
								JSONObject request = new JSONObject();
								try {
									request.put("function", "selectList");
									request.put("mobile_key", "");
									request.put("resource", "");
									request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
									request.put("query", "");
									request.put("start", page);
									request.put("limit", 5);
									request.put("order", "");
									request.put("mode", "");
									request.put("filtro", filtro);
									Log.d("request", request.toString());



									ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
									executor.execute(request);

									pd = new ProgressDialog(MenuActivity.this);
									pd.setCancelable(false);
									pd.setMessage("Cargando formularios, por favor espere un momento!!!");
									pd.show();



								} catch (JSONException e) {
									Toast.makeText(getApplicationContext(),
											"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
									e.printStackTrace();
								}

							}
						}


						else {
							Toast.makeText(getApplicationContext(), "No hay conexion a internet", Toast.LENGTH_SHORT).show();    						
						}

					}
				});

				final ListView listView = (ListView) MenuActivity.this.findViewById(R.id.lvMenuProspectos);

				Form data[] = new Form[]
						{
						new Form(1, 0, 0, "",
								"", "", "",
								"", "", "","",
								"", "",
								"",
								"",
								"",
								"", "",
			        			"Creado", "", 0,
			        			0,
			        			0,
			        			"",
			        			"",
			        			"",false,"false")
			        };
			        
			        adapter = new ListAdapter(MenuActivity.this,R.layout.listview_item_row, data);
			           
			        
			        listaFormularios = (ListView)MenuActivity.this.findViewById(R.id.lvMenuProspectos);
			         
			        View header = (View)getLayoutInflater().inflate(R.layout.listview_list_row, null);
			        listaFormularios.addHeaderView(header);
			        
			        listaFormularios.setAdapter(adapter);
			        
    	            
    	            // ListView Item Click Listener
			        listaFormularios.setOnItemClickListener(new OnItemClickListener() {

			        	@Override
			        	public void onItemClick(AdapterView<?> parent, View view,
			        			int position, long id) {

			        		// ListView Clicked item index

			        		if(position>0 && adapter.getCount()>1)
			        		{

			        			// ListView Clicked item value
			        			Form  itemValue = (Form) listView.getItemAtPosition(position);

			        			// Show Alert 
			        			isListForm=true;
			        			modo="editando";
			        			fillForm(itemValue);

			        			try {
			        				Log.i("SELECCIONADO",itemValue.toJSON().toString());
			        			} catch (JSONException e) {
			        				// TODO Auto-generated catch block
			        				e.printStackTrace();
			        			}
			        			/*Toast.makeText(getApplicationContext(),
    	                		   "Position :"+itemPosition+"  ListItem : " +itemValue.getNombre() , Toast.LENGTH_LONG)
    	                		   .show();*/

			        		}
			        	}
    	    
    	             }); 
    	            
    	            Button atras = (Button)  MenuActivity.this.findViewById(R.id.button1);
    				atras.setOnClickListener(new OnClickListener() {
    					
    					
    					@Override
    					public void onClick(View v) {
    						prefs = PreferenceManager
    		    					.getDefaultSharedPreferences(getApplicationContext());
    						if(page>0)
    						{
    							page--;
    							JSONObject request = new JSONObject();
        						try {
        							request.put("function", "selectList");
        							request.put("mobile_key", "");
        							request.put("resource", "");
        							request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
        							request.put("query", "");
        							request.put("start", page);
        							request.put("limit", 5);
        							request.put("order", "");
        							request.put("mode", "");
        							request.put("filtro", filtro);
        							Log.d("request", request.toString());
        							
        							pd = new ProgressDialog(MenuActivity.this);
        				    		pd.setCancelable(false);
        							pd.setMessage("Enviando información, por favor espere un momento!!!");
        							pd.show();
        							ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
        				    		executor.execute(request);
        						} catch (JSONException e) {
        							Toast.makeText(getApplicationContext(),
        									"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
        							e.printStackTrace();
        						}
    						}
    						else
    						{
    							Toast.makeText(getApplicationContext(),
    									"No hay mas paginas hacia atras.", Toast.LENGTH_LONG).show();
    						}
    						
    					}
    				});
    				
    				
    				Button siguiente = (Button)  MenuActivity.this.findViewById(R.id.button2);
    				siguiente.setOnClickListener(new OnClickListener() {
    					

    					@Override
    					public void onClick(View v) {
    						prefs = PreferenceManager
    		    					.getDefaultSharedPreferences(getApplicationContext());
    						
    						if(page<Totalpage -1 )
    						{
    							page++;
    							JSONObject request = new JSONObject();
        						try {
        							request.put("function", "selectList");
        							request.put("mobile_key", "");
        							request.put("resource", "");
        							request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
        							request.put("query", "");
        							request.put("start", page);
        							request.put("limit", 5);
        							request.put("order", "");
        							request.put("mode", "");
        							request.put("filtro", filtro);
        							Log.d("request", request.toString());
        							
        							pd = new ProgressDialog(MenuActivity.this);
        				    		pd.setCancelable(false);
        							pd.setMessage("Enviando información, por favor espere un momento!!!");
        							pd.show();
        							ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
        				    		executor.execute(request);
        						} catch (JSONException e) {
        							Toast.makeText(getApplicationContext(),
        									"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
        							e.printStackTrace();
        						}
    						}
    						else
    						{
    							Toast.makeText(getApplicationContext(),
    									"No hay mas paginas hacia adelante.", Toast.LENGTH_LONG).show();
    						}
    					}
    				});
    				
    				ImageView salirForm = (ImageView)  MenuActivity.this.findViewById(R.id.ImageView01Lis);
    				salirForm.setOnClickListener(new OnClickListener() {
    	
    					@Override
    					public void onClick(View v) {
    						
    						
    						if(isBack==true)
    						{

    							isBack=false;
    							MenuActivity.this.setContentView(R.layout.activity_menu);

    							MapButton = (Button) MenuActivity.this.findViewById(R.id.menu_btn_map);
    							MapButton.setOnClickListener(MenuActivity.this);


    							importButton = (Button) MenuActivity.this.findViewById(R.id.menu_btn_video);
    							importButton.setOnClickListener(MenuActivity.this);
    							importButton.setText("Formularios sin enviar: "+"\n"+VariablesdeSesion.getInstance().getContadorFormularios());
    							importButton.setTextSize(12);


    							googleMapButton = (Button) MenuActivity.this.findViewById(R.id.Button01);
    							googleMapButton.setOnClickListener(MenuActivity.this);


    							bla = (ImageView) MenuActivity.this.findViewById(R.id.imageView2);
    							bla.setOnClickListener(MenuActivity.this);

    							tareasButton = (Button) MenuActivity.this.findViewById(R.id.Button02);
    							tareasButton.setOnClickListener(MenuActivity.this);
    							
    							ButtonList = (Button) MenuActivity.this.findViewById(R.id.Button03);
    							ButtonList.setOnClickListener(MenuActivity.this);
    							
    							tareasButtonGuarda = (Button) findViewById(R.id.ButtonGuarda);
    							//tareasButtonGuarda.setOnClickListener(this);
    							tareasButtonGuarda.setVisibility(View.INVISIBLE);

    						}    					
    					}
    				});     	
    		}    			
    	});
    }

	private void logicUIGuarda()
    {
    	this.runOnUiThread(new Runnable() {
    		@Override
    		    public void run() {
    			
    		        MenuActivity.this.setContentView(R.layout.informe_guarda);
    		        
    				TextView fechaderegistroLocal = (TextView)  MenuActivity.this.findViewById(R.id.fecha);
    				
    				GregorianCalendar c = new GregorianCalendar();
    				String s = "" + c.get(GregorianCalendar.MINUTE);
    				if (c.get(GregorianCalendar.MINUTE) < 10)
    					s = "0" + c.get(GregorianCalendar.MINUTE);
    				fechaderegistroLocal.setText(c.get(GregorianCalendar.YEAR) + "-"
    						+ c.get(GregorianCalendar.MONTH) + "-"
    						+ c.get(GregorianCalendar.DAY_OF_MONTH) + " "
    						+ c.get(GregorianCalendar.HOUR_OF_DAY) + ":" + s);
    				Spinner idSucursal = (Spinner)  MenuActivity.this
    						.findViewById(R.id.codigoPuesto);
    				ArrayList<String> stringsLocal = new ArrayList<String>();
    				stringsLocal.add("Identificación de la sucursal");
    				stringsLocal.add("8637");
    				stringsLocal.add("820");
    				stringsLocal.add("2488");
    				
    				idSucursal.setAdapter(new ArrayAdapter<String>(
    						getApplicationContext(), R.layout.spinner_item, stringsLocal));
    				idSucursal
    						.setOnItemSelectedListener(new OnItemSelectedListener() {

    							@Override
    							public void onNothingSelected(AdapterView<?> parent) {
    								
    							}

    							@Override
    							public void onItemSelected(AdapterView<?> parent,
    									View view, int position, long id) {
    								//if (position > 0)
    									
    							}
    						});
    				ArrayList<String> strings2Local = new ArrayList<String>();
    				strings2Local.add("Activo I");
    				strings2Local.add("Vehiculos");
    				strings2Local.add("Control de rondas");
    			
    				Spinner activo = (Spinner)  MenuActivity.this
    						.findViewById(R.id.activo);
    				activo.setAdapter(new ArrayAdapter<String>(
    						getApplicationContext(), R.layout.spinner_item, strings2Local));
    				activo
    						.setOnItemSelectedListener(new OnItemSelectedListener() {
    							

    							@Override
    							public void onNothingSelected(AdapterView<?> parent) {
    							}

    							@Override
    							public void onItemSelected(AdapterView<?> parent,
    									View view, int position, long id) {
    								//if (position > 0)
    									
    							}
    						});
    				
    				Estado = (Spinner)  MenuActivity.this.findViewById(R.id.Estado);
    				
    				strings5 = new ArrayList<String>();
    				strings5.add("CREADO");

    				ArrayList<String> strings3Local = new ArrayList<String>();
    				strings3Local.add("Activo pregunta II");
    				strings3Local.add("Vehiculos");
    				strings3Local.add("Control de rondas");
    				Spinner otroDos = (Spinner)  MenuActivity.this.findViewById(R.id.spinnerPreguntaDos);
    				otroDos.setAdapter(new ArrayAdapter<String>(
    						getApplicationContext(), R.layout.spinner_item, strings3Local));
    				otroDos.setOnItemSelectedListener(new OnItemSelectedListener() {
    					

    					@Override
    					public void onNothingSelected(AdapterView<?> parent) {
    					}

    					@Override
    					public void onItemSelected(AdapterView<?> parent, View view,
    							int position, long id) {
    						
    					}
    				});
    				
    				logo= (ImageView)MenuActivity.this.findViewById(R.id.imageView2);
    				//buscar = (AutoCompleteTextView)  MenuActivity.this.findViewById(R.id.buscar);
    				acepto= (CheckBox) MenuActivity.this.findViewById(R.id.checkBox1);
    				addAdapterToViews();
    				
    				submit = (Button)  MenuActivity.this.findViewById(R.id.foto);
    				submit.setOnClickListener(new OnClickListener() {
    					

    					@Override
    					public void onClick(View v) {
    						
    					}
    				});
    				
    				ImageView menuForm= (ImageView)MenuActivity.this.findViewById(R.id.ImageView01InfGuarda);
    				menuForm.setOnClickListener(new OnClickListener() {

    					@Override
    					public void onClick(View v) {
    						
    						if(isBack==true)
    						{
    							isBack=false;
    							MenuActivity.this.setContentView(R.layout.activity_menu);

    							MapButton = (Button) MenuActivity.this.findViewById(R.id.menu_btn_map);
    							MapButton.setOnClickListener(MenuActivity.this);


    							importButton = (Button) MenuActivity.this.findViewById(R.id.menu_btn_video);
    							importButton.setOnClickListener(MenuActivity.this);
    							if(reggister)
    							{
    								contador=Integer.parseInt(VariablesdeSesion.getInstance().getContadorFormularios());
    								resultCount="Formularios sin enviar: "+"\n"+String.valueOf(contador);
    								reggister=false;
    							}
    							importButton.setText(resultCount);
    							importButton.setTextSize(12);

    							googleMapButton = (Button) MenuActivity.this.findViewById(R.id.Button01);
    							googleMapButton.setOnClickListener(MenuActivity.this);


    							bla = (ImageView) MenuActivity.this.findViewById(R.id.imageView2);
    							bla.setOnClickListener(MenuActivity.this);

    							tareasButton = (Button) MenuActivity.this.findViewById(R.id.Button02);
    							tareasButton.setOnClickListener(MenuActivity.this);
    							
    							ButtonList = (Button) MenuActivity.this.findViewById(R.id.Button03);
    							ButtonList.setOnClickListener(MenuActivity.this);
    							
    							tareasButtonGuarda = (Button) findViewById(R.id.ButtonGuarda);
    							//tareasButtonGuarda.setOnClickListener(this);
    							tareasButtonGuarda.setVisibility(View.INVISIBLE);

    						}   						
    					}
    				});
    				
    		    }
    		});
    	
    	/*Button back=(Button)MenuActivity.this.findViewById(R.id.ButtonSaveGu);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				limpiarForm();
				form=new Form();
				strings5 = new ArrayList<String>();
				strings5.add("CREADO");// si esta creado no vuelve
				Estado.setAdapter(new ArrayAdapter<String>(
						getApplicationContext(), R.layout.spinner_item, strings5));

				

			}
		});*/
		
		Button firmar=(Button)MenuActivity.this.findViewById(R.id.ButtonFimarGu);
		firmar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				 runOnUiThread(new Runnable() {
					 public void run() {

						 Context mContext = MenuActivity.this;
						 LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
						 View layout = inflater.inflate(R.layout.firma,(ViewGroup) findViewById(R.id.padre));;
						 
						    mContent = (LinearLayout) layout.findViewById(R.id.linearLayoutsign);
					        mSignature = new signature(MenuActivity.this, null);
					        mSignature.setBackgroundColor(Color.WHITE);
					        mContent.addView(mSignature, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
					        mClear = (Button)layout.findViewById(R.id.clear);
					        mGetSign = (Button)layout.findViewById(R.id.getsign);
					        mGetSign.setEnabled(false);
					        mCancel = (Button)layout.findViewById(R.id.cancel);
					        mView = mContent;
					 
					        mClear.setOnClickListener(new OnClickListener() 
					        {        
					            public void onClick(View v) 
					            {
					                Log.v("log_tag", "Panel Cleared");
					                mSignature.clear();
					                mGetSign.setEnabled(false);
					            }
					        });
					 
					        mGetSign.setOnClickListener(new OnClickListener() 
					        {        
					            public void onClick(View v) 
					            {
					                Log.v("log_tag", "Panel Saved");
					                //boolean error = captureSignature();
					                //if(!error){
					                    mView.setDrawingCacheEnabled(true);
					                    mSignature.save(mView);
					                    //mypath.delete();
					                    Bundle b = new Bundle();
					                    b.putString("status", "done");
					                    b.putString("resultado",result);
					                    Intent intent = new Intent();
					                    intent.putExtras(b);
					                    setResult(RESULT_OK,intent);   
					                    alertDialog.cancel();
					                //}
					            }
					        });
					 
					        mCancel.setOnClickListener(new OnClickListener() 
					        {        
					            public void onClick(View v) 
					            {
					                Log.v("log_tag", "Panel Canceled");
					                Bundle b = new Bundle();
					                b.putString("status", "cancel");
					                Intent intent = new Intent();
					                intent.putExtras(b);
					                setResult(RESULT_OK,intent);  
					                alertDialog.cancel();
					            }
					        });


						 builder = new AlertDialog.Builder(mContext);
						 builder.setView(layout);
						 alertDialog = builder.create();
						 alertDialog.show();


					 }
				 });

			}
		});
		
		Button buttonFoto1 = (Button) MenuActivity.this
				.findViewById(R.id.buttonFotoNovedad);
		buttonFoto1.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent cameraIntent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(cameraIntent,
						CAMERA_REQUEST_CUATRO);
			}
		});
		Button buttonFoto2 = (Button) MenuActivity.this
				.findViewById(R.id.foto);
		buttonFoto2
		.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent cameraIntent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(cameraIntent,
						CAMERA_REQUEST_CINCO);
			}
		});
		

    }
	
    private void logicUI()
    {
    	this.runOnUiThread(new Runnable() {
    		@Override
    		    public void run() {
    			
    		        MenuActivity.this.setContentView(R.layout.informe_user);
    		        s=new Search(MenuActivity.this.getBaseContext());
    		        nombre = (EditText)  MenuActivity.this.findViewById(R.id.nombre);
    				apellido = (EditText)  MenuActivity.this.findViewById(R.id.apellido);
    				documento = (EditText)  MenuActivity.this.findViewById(R.id.Documento);
    				numeroTelefonico1 = (EditText)  MenuActivity.this
    						.findViewById(R.id.NumeroTelefonico1);
    				numeroTelefonico2 = (EditText)  MenuActivity.this
    						.findViewById(R.id.NumeroTelefonico2);
    				numeroCelular1 = (EditText)  MenuActivity.this.findViewById(R.id.NumeroCelular1);
    				numeroCelular2 = (EditText)  MenuActivity.this.findViewById(R.id.NumeroCelular2);
    				mensajeProximoContacto = (EditText)  MenuActivity.this
    						.findViewById(R.id.MensajeProximoContacto);
    				observaciones = (EditText)  MenuActivity.this.findViewById(R.id.Observaciones);
    				fechaderegistro = (TextView)  MenuActivity.this.findViewById(R.id.Fechaderegistro);
    				lblAvisoLegal = (TextView)  MenuActivity.this.findViewById(R.id.lblAvisoLegal);   				
    				//lyAvisoLegal = (LinearLayout)  MenuActivity.this.findViewById(R.id.);   				
    				
    				direccion=(EditText)  MenuActivity.this.findViewById(R.id.editTextDir);
    				correo=(EditText)  MenuActivity.this.findViewById(R.id.editTextEmail);   				
    				
    				GregorianCalendar c = new GregorianCalendar();
    				String s = "" + c.get(GregorianCalendar.MINUTE);
    				if (c.get(GregorianCalendar.MINUTE) < 10)
    					s = "0" + c.get(GregorianCalendar.MINUTE);
    				fechaderegistro.setText(c.get(GregorianCalendar.YEAR) + "-"
    						+ c.get(GregorianCalendar.MONTH) + "-"
    						+ c.get(GregorianCalendar.DAY_OF_MONTH) + " "
    						+ c.get(GregorianCalendar.HOUR_OF_DAY) + ":" + s);
    				
    				operadorActualdeTelevision = (Spinner)  MenuActivity.this
    						.findViewById(R.id.OperadorActualdeTelevision);
    				Cobertura = (Spinner)MenuActivity.this.findViewById(R.id.Cobertura);
    				ProductoInteres = (Spinner)MenuActivity.this.findViewById(R.id.ProductoInteres);
    				
    				strings6 = new ArrayList<String>();
    				strings6.add("Prospecto ubicado en zona cobertura NET");
    				strings6.add("Si");
    				strings6.add("No");
    				Cobertura.setAdapter(new ArrayAdapter<String>(
    						getApplicationContext(), R.layout.spinner_item,strings6));
    				Cobertura
    				.setOnItemSelectedListener(new OnItemSelectedListener() {

						@Override
						public void onNothingSelected(AdapterView<?> parent) {
							Toast.makeText(getApplicationContext(),
									"El prospecto es obligatorio!",
									Toast.LENGTH_SHORT).show();
						}

						@Override
						public void onItemSelected(AdapterView<?> parent,
								View view, int position, long id) {
							if (position > 0)							
								 coberturaR= strings6.get(position);
							
							if(coberturaR=="Si")
								coberturaR="true";
							
							else
								coberturaR="false";
							
								
						}
					});
    				
    				strings7 = new ArrayList<String>();
    				strings7.add("Producto Interes");
    				strings7.add("TV");
    				strings7.add("NET");
    				strings7.add("DIRECT TV TOTAL");
    				ProductoInteres.setAdapter(new ArrayAdapter<String>(
    						getApplicationContext(), R.layout.spinner_item,strings7));
    				ProductoInteres
					.setOnItemSelectedListener(new OnItemSelectedListener() {

						@Override
						public void onNothingSelected(AdapterView<?> parent) {
							Toast.makeText(getApplicationContext(),
									"El producto de interes es obligatorio!",
									Toast.LENGTH_SHORT).show();
						}

						@Override
						public void onItemSelected(AdapterView<?> parent,
								View view, int position, long id) {
							if (position > 0)
								 productointeresR= strings7.get(position);
						}
					});
    				
    				strings = new ArrayList<String>();
    				strings.add("Operador Actual de Television");
    				strings.add("CLARO");
    				strings.add("UNE");
    				strings.add("MOVISTAR");
    				strings.add("ETB");
    				strings.add("OTROS");
    				operadorActualdeTelevision.setAdapter(new ArrayAdapter<String>(
    						getApplicationContext(), R.layout.spinner_item, strings));
    				operadorActualdeTelevision
    						.setOnItemSelectedListener(new OnItemSelectedListener() {

    							@Override
    							public void onNothingSelected(AdapterView<?> parent) {
    								Toast.makeText(getApplicationContext(),
    										"Operador Actual de Television es obligatorio!",
    										Toast.LENGTH_SHORT).show();
    							}

    							@Override
    							public void onItemSelected(AdapterView<?> parent,
    									View view, int position, long id) {
    								if (position > 0)
    									operadorR = strings.get(position);
    							}
    						});
    				strings2 = new ArrayList<String>();
    				strings2.add("Tipo de Contacto a Realizar");
    				strings2.add("Llamada");
    				strings2.add("Visita Personal");
    				strings2.add("Correo Electronico");    				
    				strings2.add("Otro");
    				tipodeContactoaRealizar = (Spinner)  MenuActivity.this
    						.findViewById(R.id.TipodeContactoaRealizar);
    				tipodeContactoaRealizar.setAdapter(new ArrayAdapter<String>(
    						getApplicationContext(), R.layout.spinner_item, strings2));
    				tipodeContactoaRealizar
    						.setOnItemSelectedListener(new OnItemSelectedListener() {
    							

    							@Override
    							public void onNothingSelected(AdapterView<?> parent) {
    							}

    							@Override
    							public void onItemSelected(AdapterView<?> parent,
    									View view, int position, long id) {
    								if (position > 0)
    									contactoaRealizarR = strings2.get(position);
    							}
    						});
    				
    				Estado = (Spinner)  MenuActivity.this.findViewById(R.id.Estado);
    				
    				strings5 = new ArrayList<String>();
    				strings5.add("CREADO");

    				strings4 = new ArrayList<String>();
    				strings4.add("Tipo Documento");
    				strings4.add("Cedula de Ciudadania");
    				strings4.add("Cedula de Extranjeria");
    				tipoDocumento = (Spinner)  MenuActivity.this.findViewById(R.id.tipoDocumento);
    				tipoDocumento.setAdapter(new ArrayAdapter<String>(
    						getApplicationContext(), R.layout.spinner_item, strings4));
    				tipoDocumento.setOnItemSelectedListener(new OnItemSelectedListener() {
    					

    					@Override
    					public void onNothingSelected(AdapterView<?> parent) {
    					}

    					@Override
    					public void onItemSelected(AdapterView<?> parent, View view,
    							int position, long id) {
    						if (position > 0)
    							tipoDocumentoR = strings4.get(position);
    					}
    					
    					
    				});
    				
    				//Abrir el pop de aviso legal Por Ing. Cesar Prieto.
    				
    				final Context context = MenuActivity.this;
    				
    				Button btnaceptar;
    				
    				
    				lblAvisoLegal.setOnClickListener(new OnClickListener() {

    					@Override
    					public void onClick(View v) {
    						LayoutInflater layoutInflater 
    						= (LayoutInflater)getBaseContext()
    						.getSystemService(LAYOUT_INFLATER_SERVICE);  
    						View popupView = layoutInflater.inflate(R.layout.aviso_legal, null);  
    						final PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, 
    								ViewGroup.LayoutParams.MATCH_PARENT, true); 

    						popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
    						Button btnDismiss = (Button)popupView.findViewById(R.id.btnAceptar);
    						btnDismiss.setOnClickListener(new Button.OnClickListener(){

    							@Override
    							public void onClick(View v) {
    								// TODO Auto-generated method stub
    								popupWindow.dismiss();
									acepto.setChecked(true);
								}});


							popupWindow.showAsDropDown(ProductoInteres, Gravity.CENTER_HORIZONTAL,Gravity.CENTER_VERTICAL);

						}});

    				

    				
    				Estado.setAdapter(new ArrayAdapter<String>(
    						getApplicationContext(), R.layout.spinner_item, strings5));
    				Estado.setOnItemSelectedListener(new OnItemSelectedListener() {
    					

    					@Override
    					public void onNothingSelected(AdapterView<?> parent) {
    					}

    					@Override
    					public void onItemSelected(AdapterView<?> parent, View view,
    							int position, long id) {
    						if (position > 0)
    							estadoR = strings5.get(position);
    					}
    				});
    				
    				timePicker = (Button)  MenuActivity.this.findViewById(R.id.buttonhora);
    				datePicker = (Button)  MenuActivity.this.findViewById(R.id.btnAceptar);
    				cal = Calendar.getInstance();
    				year = cal.get(Calendar.YEAR);
    				month = cal.get(Calendar.MONTH);
    				day = cal.get(Calendar.DAY_OF_MONTH);
    				hour = cal.get(Calendar.HOUR_OF_DAY);
    				minute = cal.get(Calendar.MINUTE);
    				datePicker.setOnClickListener(new OnClickListener() {
    					@SuppressWarnings("deprecation")
						@Override
    					public void onClick(View v) {
    						showDialog(DATE_DIALOG_ID);
    					}
    				});
    				timePicker.setOnClickListener(new OnClickListener() {
    					@SuppressWarnings("deprecation")
						@Override
    					public void onClick(View v) {
    						showDialog(TIME_DIALOG_ID);
    					}
    				});
    				logo= (ImageView)MenuActivity.this.findViewById(R.id.imageView2);
    				//buscar = (AutoCompleteTextView)  MenuActivity.this.findViewById(R.id.buscar);
    				acepto= (CheckBox) MenuActivity.this.findViewById(R.id.checkBox1);
    				addAdapterToViews();
    				
    				submit = (Button)  MenuActivity.this.findViewById(R.id.submit);
    				submit.setOnClickListener(new OnClickListener() {
    					

    					@Override
    					public void onClick(View v) {
    						prefs = PreferenceManager
    		    					.getDefaultSharedPreferences(getApplicationContext());
    						
    						
    						
    						if (nombre.getText().toString().equalsIgnoreCase(""))
    							Toast.makeText(getApplicationContext(),
    									"Nombre es obligatorio!", Toast.LENGTH_SHORT)
    									.show();
    						else if (apellido.getText().toString().equalsIgnoreCase(""))
    							Toast.makeText(getApplicationContext(),
    									"Apellido es obligatorio!", Toast.LENGTH_SHORT)
    									.show();
    						else if (numeroCelular1.getText().toString()
    								.equalsIgnoreCase(""))
    							Toast.makeText(getApplicationContext(),
    									"Numero Celular 1 es obligatorio!",
    									Toast.LENGTH_SHORT).show();
    						else if (numeroTelefonico1.getText().toString()
    								.equalsIgnoreCase(""))
    							Toast.makeText(getApplicationContext(),
    									"Numero Telefono 1 es obligatorio!",
    									Toast.LENGTH_SHORT).show();
    						else if (operadorR.equalsIgnoreCase("") )
    							Toast.makeText(getApplicationContext(),
    									"Operador Actual de Television es obligatorio!",
    									Toast.LENGTH_SHORT).show();
    						else if (coberturaR.equalsIgnoreCase("") )
    							Toast.makeText(getApplicationContext(),
    									"Zona de cobertura es obligatorio!",
    									Toast.LENGTH_SHORT).show();
    						else if (productointeresR.equalsIgnoreCase("") )
    							Toast.makeText(getApplicationContext(),
    									"Producto de interes es obligatorio!",
    									Toast.LENGTH_SHORT).show();
    						else if (hourFinal.toString().equalsIgnoreCase(""))
    							Toast.makeText(getApplicationContext(),
    									"La hora del poximo contacto es obligatoria!", Toast.LENGTH_SHORT)
    									.show();
    						else if (date.toString().equalsIgnoreCase("") || date==null)
    							Toast.makeText(getApplicationContext(),
    									"El Fecha del proximo contacto es obligatoria!", Toast.LENGTH_SHORT)
    									.show();
    						
    						else if (acepto.isChecked()==false)     								
    							Toast.makeText(getApplicationContext(),
    									"Terminos y condiciones es obligatorio!", Toast.LENGTH_SHORT)
    									.show();
    						else {
    							JSONObject encuesta = new JSONObject();
    							
    							try {
									
									encuesta.put("mobile_key", "");
	    							encuesta.put("resource","");
	    							encuesta.put("names", removeAcento(nombre.getText()
	    									.toString()));
	    							encuesta.put("surnames", removeAcento(apellido
	    									.getText().toString()));
	    							encuesta.put("type_id", tipoDocumentoR);
	    							encuesta.put("prospect_id", documento.getText()
	    									.toString());
	    							encuesta.put("telephone1", numeroTelefonico1.getText()
	    									.toString());
	    							encuesta.put("telephone2", numeroTelefonico2.getText()
	    									.toString());
	    							encuesta.put("celular1", numeroCelular1.getText()
	    									.toString());
	    							encuesta.put("celular2", numeroCelular2.getText()
	    									.toString());
	    							encuesta.put("coverage",coberturaR);
	    							encuesta.put("product",productointeresR);
	    							//encuesta.put("date_time", fechaderegistro.getText() );
	    							encuesta.put("operator", operadorR);
	    							encuesta.put("next_contact", date + " " + hourFinal);
	    							encuesta.put("type_contact", contactoaRealizarR);
	    							encuesta.put("msg_contact", removeAcento(mensajeProximoContacto
	    									.getText().toString()));
	    							encuesta.put("observations", removeAcento(observaciones.getText()
	    									.toString()));
	    							encuesta.put("status", estadoR);
	    							encuesta.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
	    							encuesta.put("date_time", new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()));


    								encuesta.put("address", removeAcento(direccion.getText().toString()));
    								encuesta.put("email", removeAcento(correo.getText().toString()));
    								encuesta.put("sign", result);
    								encuesta.put("user", prefs.getString("idUsuario",""));	    							
	    							
	    						
	    							if(lastlocation!=null)
	    							{
	    								encuesta.put("speed", (int) lastlocation.getSpeed());
	    								encuesta.put("heading", (int) lastlocation.getBearing());
	    								encuesta.put("precision", (int) lastlocation.getAccuracy());
	    								encuesta.put("latitude", String.valueOf(lastlocation.getLatitude()));
		    							encuesta.put("longitude", String.valueOf(lastlocation.getLongitude()));
	  
	    							}
	    							else
	    							{
	    								encuesta.put("speed", (int) 0);
	    								encuesta.put("heading", (int) 0);
	    								encuesta.put("precision", (int) 0);
	    								encuesta.put("latitude", latitud);
		    							encuesta.put("longitude", longitud);
	    								
	    								
	    							}
	    							//botonSeleccionado="crear";
	    							
	    							if(modo.trim().equalsIgnoreCase("editando"))
	    							{
	    								encuesta.put("server_id", form.getServer_id());
		    							encuesta.put("local_id", form.getLocal_id());
		    							encuesta.put("function", "updateForm");
	    								
	    							}
	    							else
	    							{
	    								encuesta.put("function", "registerForm");
	    							}
	    							
	    							if(acepto.isChecked())
	    							{
	    								encuesta.put("agree", "true");
	    								
	    							}
	    							else
	    							{
	    								encuesta.put("agree", "false");
	    							}
	    							
	    							reggister=true;
	    							contador=Integer.parseInt(VariablesdeSesion.getInstance().getContadorFormularios());	    							
	    							contador=contador+1;
	    							VariablesdeSesion.getInstance().setContadorFormularios(String.valueOf(contador));
	    							pd = new ProgressDialog(MenuActivity.this);
	    				    		pd.setCancelable(false);
	    							pd.setMessage("Enviando información, por favor espere un momento!!!");
	    							pd.show();
	    							
	    							
	    							Date hoy=new java.util.Date();
	    							String dateFin=date+" "+hourFinal+":10";
	    							Date dateFinal=stringTodate(dateFin);
	    							//Date afterAddingTenMins=new Date(dateFinal.getTime() - (900000));
	    							if(!dateFinal.before(hoy))
	    							{
	    								String data=nombre.getText().toString()+" "+apellido.getText().toString();
	    								notify=new Notificacion();
	    								notify.setFecha(dateFin);
	    								notify.setNombres(data);
	    								notify.setCelular(numeroCelular1.getText()
	    										.toString());
	    								configurarEvento(MenuActivity.this,numeroCelular1.getText()
	    										.toString(),dateFinal,data,notify);
	    								
	    							}
	    							ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
	    				    		executor.execute(encuesta);
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
    							
    							
    						}
    					}
    				});
    				
    				ImageView menuForm= (ImageView)MenuActivity.this.findViewById(R.id.ImageView01Inf);
    				menuForm.setOnClickListener(new OnClickListener() {

    					@Override
    					public void onClick(View v) {
    						
    						if(isBack==true)
    						{

    							isBack=false;
    							MenuActivity.this.setContentView(R.layout.activity_menu);

    							MapButton = (Button) MenuActivity.this.findViewById(R.id.menu_btn_map);
    							MapButton.setOnClickListener(MenuActivity.this);


    							importButton = (Button) MenuActivity.this.findViewById(R.id.menu_btn_video);
    							importButton.setOnClickListener(MenuActivity.this);
    							if(reggister)
    							{
    								contador = Integer.parseInt(VariablesdeSesion.getInstance().getContadorFormularios());
    								resultCount="Formularios sin enviar: "+"\n"+String.valueOf(contador);
    								reggister=false;
    							}
    							
    							importButton.setText(resultCount);
    							importButton.setTextSize(12);

    							googleMapButton = (Button) MenuActivity.this.findViewById(R.id.Button01);
    							googleMapButton.setOnClickListener(MenuActivity.this);


    							bla = (ImageView) MenuActivity.this.findViewById(R.id.imageView2);
    							bla.setOnClickListener(MenuActivity.this);

    							tareasButton = (Button) MenuActivity.this.findViewById(R.id.Button02);
    							tareasButton.setOnClickListener(MenuActivity.this);
    							
    							ButtonList = (Button) MenuActivity.this.findViewById(R.id.Button03);
    							ButtonList.setOnClickListener(MenuActivity.this);
    							
    							tareasButtonGuarda = (Button) findViewById(R.id.ButtonGuarda);
    							//tareasButtonGuarda.setOnClickListener(this);
    							tareasButtonGuarda.setVisibility(View.INVISIBLE);

    						}

    						
    						
    					}
    				});
    				
    				// sliding
    				menu = new SlidingMenu(MenuActivity.this);
    				menu.setMode(SlidingMenu.LEFT);
    				menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
    				menu.setShadowWidthRes(R.dimen.shadow_width);
    				menu.setShadowDrawable(R.drawable.shadowslidemenu);
    				menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
    				menu.setFadeEnabled(true);
    				menu.setFadeDegree(0.35f);
    				menu.setBackgroundResource(android.R.color.white);
    				menu.attachToActivity(MenuActivity.this, SlidingMenu.SLIDING_CONTENT);
    				menu.setOnClosedListener(new OnClosedListener() {

    					@Override
    					public void onClosed() {
    						mostrarMenuPrincipal(null);
    					}
    				});
    		}
    	});

    	search = (Button)  MenuActivity.this.findViewById(R.id.Button01inf);
    	search.setOnClickListener(new OnClickListener() {

    		@Override
    		public void onClick(View v) {
    			if (search.isFocused())
    				logo.setVisibility(View.GONE);
    			//else if (buscar.getText().toString().equalsIgnoreCase(""))
    				//logo.setVisibility(View.VISIBLE);

    		}
    	});

    	Button back=(Button)MenuActivity.this.findViewById(R.id.ButtonAtras);
    	back.setOnClickListener(new OnClickListener() {

    		@Override
    		public void onClick(View v) {

    			limpiarForm();
    			form=new Form();
    			strings5 = new ArrayList<String>();
    			strings5.add("CREADO");// si esta creado no vuelve
    			Estado.setAdapter(new ArrayAdapter<String>(
    					getApplicationContext(), R.layout.spinner_item, strings5));
}
    	});

    	Button firmar=(Button)MenuActivity.this.findViewById(R.id.ButtonFimar);
    	firmar.setOnClickListener(new OnClickListener() {

    		@Override
    		public void onClick(View v) {

    			runOnUiThread(new Runnable() {
    				public void run() {

    					Context mContext = MenuActivity.this;
    					LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
    					View layout = inflater.inflate(R.layout.firma,(ViewGroup) findViewById(R.id.padre));;

    					mContent = (LinearLayout) layout.findViewById(R.id.linearLayoutsign);
    					mSignature = new signature(MenuActivity.this, null);
    					mSignature.setBackgroundColor(Color.WHITE);
    					mContent.addView(mSignature, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    					mClear = (Button)layout.findViewById(R.id.clear);
    					mGetSign = (Button)layout.findViewById(R.id.getsign);
    					mGetSign.setEnabled(false);
    					mCancel = (Button)layout.findViewById(R.id.cancel);
    					mView = mContent;

    					mClear.setOnClickListener(new OnClickListener() 
    					{        
    						public void onClick(View v) 
    						{
    							Log.v("log_tag", "Panel Cleared");
    							mSignature.clear();
    							mGetSign.setEnabled(false);
    						}
    					});

    					mGetSign.setOnClickListener(new OnClickListener() 
    					{        
    						public void onClick(View v) 
    						{
    							Log.v("log_tag", "Panel Saved");
    							//boolean error = captureSignature();
    							//if(!error){
    							mView.setDrawingCacheEnabled(true);
    							mSignature.save(mView);
    							//mypath.delete();
    							Bundle b = new Bundle();
    							b.putString("status", "done");
    							b.putString("resultado",result);
    							Intent intent = new Intent();
    							intent.putExtras(b);
    							setResult(RESULT_OK,intent);   
    							alertDialog.cancel();
    							//}
    						}
    					});

    					mCancel.setOnClickListener(new OnClickListener() 
    					{        
    						public void onClick(View v) 
    						{
    							Log.v("log_tag", "Panel Canceled");
    							Bundle b = new Bundle();
    							b.putString("status", "cancel");
    							Intent intent = new Intent();
    							intent.putExtras(b);
    							setResult(RESULT_OK,intent);  
    							alertDialog.cancel();
    						}
    					});
    					builder = new AlertDialog.Builder(mContext);
    					builder.setView(layout);
    					alertDialog = builder.create();
    					alertDialog.show();
    				}
    			});
    		}
    	});
    }
    
    public void cargar_funciones(){    	
    	
		prefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		page=0;
		
		// ListView Item Click Listener
        listaFormularios.setOnItemClickListener(new OnItemClickListener() {

              @Override
              public void onItemClick(AdapterView<?> parent, View view,
                 int position, long id) {
                
               // ListView Clicked item index
               int itemPosition = position;
               
               // ListView Clicked item value
               Form  itemValue = (Form) listaFormularios.getItemAtPosition(position);
               
               // Show Alert 
               isListForm=true;
               modo="editando";
               fillForm(itemValue);
               
               try {
				Log.i("SELECCIONADO",itemValue.toJSON().toString());
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
               /*Toast.makeText(getApplicationContext(),
            		   "Position :"+itemPosition+"  ListItem : " +itemValue.getNombre() , Toast.LENGTH_LONG)
            		   .show();*/

              }

         }); 
    	
    	// sliding
		menu = new SlidingMenu(MenuActivity.this);
		menu.setMode(SlidingMenu.RIGHT);
		menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
		menu.setShadowWidthRes(R.dimen.shadow_width);
		menu.setShadowDrawable(R.drawable.shadowslidemenu);
		menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		menu.setFadeEnabled(true);
		menu.setFadeDegree(0.35f);
		menu.setBackgroundResource(android.R.color.white);
		menu.attachToActivity(MenuActivity.this, SlidingMenu.SLIDING_CONTENT);
		menu.setOnClosedListener(new OnClosedListener() {

			@Override
			public void onClosed() {
				mostrarMenuPrincipal(null);
			}
		});
		
		
		
		btnhacer=(ImageView)findViewById(R.id.hacer);
		btnhacer.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				menu.showMenu();
				mostrarMenuPrincipal(null);
			}
		});

		btnActualizar=(Button)findViewById(R.id.btnActualizar);
		btnActualizar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub   
				DetectordeInternet	objDetector = new DetectordeInternet(MenuActivity.this);
				if(objDetector.estasConectado()){
					//VariablesdeSesion.getInstance().setContadorFormularios("0");    						

					JSONObject cargar=new JSONObject();
					try {
						cargar.put("function", "sincronizar");
						sincronizar(cargar);
						ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
						executor.execute(cargar);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();							
					}

					if(VariablesdeSesion.getInstance().getContadorFormularios().equals("0"))
					{
						//Toast.makeText(getApplicationContext(), "Cargando Lista de Servicios", Toast.LENGTH_SHORT).show();
						dbHelper.Eliminar();	
						JSONObject request = new JSONObject();
						try {
							request.put("function", "selectList");
							request.put("mobile_key", "");
							request.put("resource", "");
							request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
							request.put("query", "");
							request.put("start", page);
							request.put("limit", 5);
							request.put("order", "");
							request.put("mode", "");
							request.put("filtro", filtro);
							Log.d("request", request.toString());



							ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
							executor.execute(request);

							pd = new ProgressDialog(MenuActivity.this);
							pd.setCancelable(false);
							pd.setMessage("Cargando formularios, por favor espere un momento!!!");
							pd.show();



						} catch (JSONException e) {
							Toast.makeText(getApplicationContext(),
									"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
							e.printStackTrace();
						}

					}
				}


				else {
					Toast.makeText(getApplicationContext(), "No hay conexion a internet", Toast.LENGTH_SHORT).show();    						
				}
				
				// ListView Item Click Listener
	            
	            
	             

			}
		});
		
		Button atras = (Button)  MenuActivity.this.findViewById(R.id.button1);
		atras.setOnClickListener(new OnClickListener() {
			

			@Override
			public void onClick(View v) {
				prefs = PreferenceManager
    					.getDefaultSharedPreferences(getApplicationContext());
				if(page>0)
				{
					page--;
					JSONObject request = new JSONObject();
					try {
						request.put("function", "selectList");
						request.put("mobile_key", "");
						request.put("resource", "");
						request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
						request.put("query", "");
						request.put("start", page);
						request.put("limit", 5);
						request.put("order", "");
						request.put("mode", "");
						request.put("filtro",filtro);
						Log.d("request", request.toString());
						
						pd = new ProgressDialog(MenuActivity.this);
			    		pd.setCancelable(false);
						pd.setMessage("Enviando información, por favor espere un momento!!!");
						pd.show();
						ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
			    		executor.execute(request);
					} catch (JSONException e) {
						Toast.makeText(getApplicationContext(),
								"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}
				}
				else
				{
					Toast.makeText(getApplicationContext(),
							"No hay mas paginas hacia atras.", Toast.LENGTH_LONG).show();
				}
				
			}
		});
		
		
		Button siguiente = (Button)  MenuActivity.this.findViewById(R.id.button2);
		siguiente.setOnClickListener(new OnClickListener() {
			

			@Override
			public void onClick(View v) {
				prefs = PreferenceManager
    					.getDefaultSharedPreferences(getApplicationContext());
				
				if(page<Totalpage -1 )
				{
					page++;
					JSONObject request = new JSONObject();
					try {
						request.put("function", "selectList");
						request.put("mobile_key", "");
						request.put("resource", "");
						request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
						request.put("query", "");
						request.put("start", page);
						request.put("limit", 5);
						request.put("order", "");
						request.put("mode", "");
						request.put("filtro", filtro);
						Log.d("request", request.toString());
						
						pd = new ProgressDialog(MenuActivity.this);
			    		pd.setCancelable(false);
						pd.setMessage("Enviando información, por favor espere un momento!!!");
						pd.show();
						ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
			    		executor.execute(request);
					} catch (JSONException e) {
						Toast.makeText(getApplicationContext(),
								"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}
				}
				else
				{
					Toast.makeText(getApplicationContext(),
							"No hay mas paginas hacia adelante.", Toast.LENGTH_LONG).show();
				}
			}
		});
		
		ImageView salirForm = (ImageView)  MenuActivity.this.findViewById(R.id.ImageView01Lis);
		salirForm.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				
				if(isBack==true)
				{

					isBack=false;
					MenuActivity.this.setContentView(R.layout.activity_menu);

					MapButton = (Button) MenuActivity.this.findViewById(R.id.menu_btn_map);
					MapButton.setOnClickListener(MenuActivity.this);


					importButton = (Button) MenuActivity.this.findViewById(R.id.menu_btn_video);
					importButton.setOnClickListener(MenuActivity.this);
					importButton.setText("Formularios sin enviar: "+"\n"+VariablesdeSesion.getInstance().getContadorFormularios());
					importButton.setTextSize(12);


					googleMapButton = (Button) MenuActivity.this.findViewById(R.id.Button01);
					googleMapButton.setOnClickListener(MenuActivity.this);


					bla = (ImageView) MenuActivity.this.findViewById(R.id.imageView2);
					bla.setOnClickListener(MenuActivity.this);

					tareasButton = (Button) MenuActivity.this.findViewById(R.id.Button02);
					tareasButton.setOnClickListener(MenuActivity.this);
					
					ButtonList = (Button) MenuActivity.this.findViewById(R.id.Button03);
					ButtonList.setOnClickListener(MenuActivity.this);
					
					tareasButtonGuarda = (Button) findViewById(R.id.ButtonGuarda);
					//tareasButtonGuarda.setOnClickListener(this);
					tareasButtonGuarda.setVisibility(View.INVISIBLE);

				}    					
			}
		});  
    	
    }
    
   

    public void mostrarMenuPrincipal(View button) {
    	menu.setMenu(R.layout.menu_prospectos_realizados);

    	JSONObject request = new JSONObject();
		
		menu_prospectos[] data = new menu_prospectos[8];
        try {
			request=new JSONObject("{id:10,tipo_cliente:Creado}");		
			JSONArray bla=new JSONArray();
			bla.put(request);
			request=new JSONObject("{id:11,tipo_cliente:Contacto-1}");	
			bla.put(request);
			request=new JSONObject("{id:12,tipo_cliente:Contacto-2}");	
			bla.put(request);
			request=new JSONObject("{id:13,tipo_cliente:Contacto-3}");	
			bla.put(request);
			request=new JSONObject("{id:14,tipo_cliente:Venta}");	
			bla.put(request);
			request=new JSONObject("{id:15,tipo_cliente:Declinado}");	
			bla.put(request);
			request=new JSONObject("{id:16,tipo_cliente:Fecha}");	
			bla.put(request);
			request=new JSONObject("{id:17,tipo_cliente:Nombre}");	
			bla.put(request);
			
			
			for(int i=0;i<bla.length();i++)
			{
				JSONObject xx=bla.getJSONObject(i);
				menu_prospectos t=new menu_prospectos();
				t.setTipoCliente(xx.getString("tipo_cliente"));				
				data[i]=t; 
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        
		adapter2 = new ListAdapterMenuProspectos(MenuActivity.this, R.layout.listview_menu_prospectos_realizados,data);
		ListView  listView1 = (ListView)menu.findViewById(R.id.lvMenuProspectos);
		


		listView1.setAdapter(adapter2);
		// ListView Item Click Listener
			
		

		listView1.setOnItemClickListener(new OnItemClickListener() {
			

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				

				int itemPosition = position;
				final ImageView logoEst= (ImageView)MenuActivity.this.findViewById(R.id.imageView2Est);	
				BuscarNombre = (EditText) MenuActivity.this.findViewById(R.id.txtBuscarNombres);

				if(position==0)
				{
					menu.toggle();
					logoEst.setVisibility(View.VISIBLE);     
					BuscarNombre.setEnabled(false);
					filtro="CREADO";				
					page=0;
	    			
	    			JSONObject request = new JSONObject();
					try {
						request.put("function", "listaform");
						request.put("mobile_key", "");
						request.put("resource", "");
						request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
						request.put("query", "");
						request.put("start", page);
						request.put("limit", 5);
						request.put("order", "");
						request.put("filtro",filtro);
						request.put("mode", "");
						Log.d("request", request.toString());

						pd = new ProgressDialog(MenuActivity.this);
						pd.setCancelable(false);
						pd.setMessage("Enviando información, por favor espere un momento!!!");
						pd.show();
						ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
						executor.execute(request);
					} catch (JSONException e) {
						Toast.makeText(getApplicationContext(),
								"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}
					
					
				}

            	if(position==1)
            	{
            		BuscarNombre.setEnabled(false);
            		logoEst.setVisibility(View.VISIBLE);
            		
            		filtro="CONTACTO 1";				
					page=0;
					menu.toggle();
	    			
	    			JSONObject request = new JSONObject();
					try {
						request.put("function", "listaform");
						request.put("mobile_key", "");
						request.put("resource", "");
						request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
						request.put("query", "");
						request.put("start", page);
						request.put("limit", 5);
						request.put("order", "");
						request.put("filtro",filtro);
						request.put("mode", "");
						Log.d("request", request.toString());

						pd = new ProgressDialog(MenuActivity.this);
						pd.setCancelable(false);
						pd.setMessage("Enviando información, por favor espere un momento!!!");
						pd.show();
						ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
						executor.execute(request);
					}
					catch (JSONException e) {
						Toast.makeText(getApplicationContext(),
								"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}

							
            	}
            	
            	if(position==2)
            	{
            		menu.toggle();
            		filtro="CONTACTO 2";				
					page=0;
	    			
	    			JSONObject request = new JSONObject();
					try {
						request.put("function", "listaform");
						request.put("mobile_key", "");
						request.put("resource", "");
						request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
						request.put("query", "");
						request.put("start", page);
						request.put("limit", 5);
						request.put("order", "");
						request.put("filtro",filtro);
						request.put("mode", "");
						Log.d("request", request.toString());

						pd = new ProgressDialog(MenuActivity.this);
						pd.setCancelable(false);
						pd.setMessage("Enviando información, por favor espere un momento!!!");
						pd.show();
						ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
						executor.execute(request);
					}
					catch (JSONException e) {
						Toast.makeText(getApplicationContext(),
								"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}
            	}        	
            	
            	if(position==3)
            	{
            		menu.toggle();
            		filtro="CONTACTO 3";				
					page=0;
	    			
	    			JSONObject request = new JSONObject();
					try {
						request.put("function", "listaform");
						request.put("mobile_key", "");
						request.put("resource", "");
						request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
						request.put("query", "");
						request.put("start", page);
						request.put("limit", 5);
						request.put("order", "");
						request.put("filtro",filtro);
						request.put("mode", "");
						Log.d("request", request.toString());

						pd = new ProgressDialog(MenuActivity.this);
						pd.setCancelable(false);
						pd.setMessage("Enviando información, por favor espere un momento!!!");
						pd.show();
						ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
						executor.execute(request);
					}
					catch (JSONException e) {
						Toast.makeText(getApplicationContext(),
								"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}
            	}
            	
            	if(position==4)
            	{
            		menu.toggle();
            		filtro="VENTA";				
					page=0;
	    			
	    			JSONObject request = new JSONObject();
					try {
						request.put("function", "listaform");
						request.put("mobile_key", "");
						request.put("resource", "");
						request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
						request.put("query", "");
						request.put("start", page);
						request.put("limit", 5);
						request.put("order", "");
						request.put("filtro",filtro);
						request.put("mode", "");
						Log.d("request", request.toString());

						pd = new ProgressDialog(MenuActivity.this);
						pd.setCancelable(false);
						pd.setMessage("Enviando información, por favor espere un momento!!!");
						pd.show();
						ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
						executor.execute(request);
					}
					catch (JSONException e) {
						Toast.makeText(getApplicationContext(),
								"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}
            	}
            	
            	if(position==5)
            	{
            		menu.toggle();
            		filtro="DECLINADO";				
					page=0;
	    			
	    			JSONObject request = new JSONObject();
					try {
						request.put("function", "listaform");
						request.put("mobile_key", "");
						request.put("resource", "");
						request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
						request.put("query", "");
						request.put("start", page);
						request.put("limit", 5);
						request.put("order", "");
						request.put("filtro",filtro);
						request.put("mode", "");
						Log.d("request", request.toString());

						pd = new ProgressDialog(MenuActivity.this);
						pd.setCancelable(false);
						pd.setMessage("Enviando información, por favor espere un momento!!!");
						pd.show();
						ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
						executor.execute(request);
					}
					catch (JSONException e) {
						Toast.makeText(getApplicationContext(),
								"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}
            	}
            	
            	if(position==6)
            	{
            		BuscarNombre.setEnabled(false);
            		//Toast.makeText(getApplicationContext(), "Nombre", Toast.LENGTH_SHORT).show();

            		logoEst.setVisibility(View.VISIBLE);            		
            		//estPlace1.setEnabled(false);
            		
            		showDialog(DATE_4_ID);      
            		
            		
            	}
            	if(position==7)
            	{
            		logoEst.setVisibility(View.INVISIBLE);
            		menu.toggle();
        			
        			BuscarNombre.setEnabled(true);
        			
        			BuscarNombre.addTextChangedListener(new TextWatcher() {        				
        				

        				@Override
        				public void onTextChanged(CharSequence s, int start, int before, int count) {         					
        					
        					
        					JSONObject request = new JSONObject();
        					try {
        						request.put("function", "AutocompletarNombres");
        						request.put("user", prefs.getString("idUsuario", ""));
        						request.put("nombre", BuscarNombre.getText().toString());   						
        						modo = "consultanombres";

        						ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
        						executor.execute(request);				


        					} catch (JSONException e) {
        						Toast.makeText(getApplicationContext(),
        								"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
        						e.printStackTrace();
        					}
        					
        					
        					

        				}

        				@Override
        				public void beforeTextChanged(CharSequence s, int start, int count,
        						int after) {
        					// TODO Auto-generated method stub

        				}

        				@Override
        				public void afterTextChanged(Editable s) {
        					// TODO Auto-generated method stub

        				}
        			});
    				

            	}
			}
		
		});
		

    }
    

    
    protected void setMenu(int listaFormularios2) {
		// TODO Auto-generated method stub
		
	}

	private DatePickerDialog.OnDateSetListener datePickerListener4 = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			dateactual = selectedYear + "-" + pad((selectedMonth + 1)) + "-"
					+ pad(selectedDay);
			date4=dateactual;
			
			menu.toggle();
			
			JSONObject resultado;
			DatabaseControl dbc = new DatabaseControl(MenuActivity.this);
			dbc.open();		
			resultado = dbc.getFormByFecha(date4,Integer.parseInt(prefs.getString("idUsuario", "")));
			dbc.close();
			
			JSONArray data = new JSONArray();
			data = resultado.optJSONArray("data");
			
			Form[] forms =new Form[data.length()];
			
			for(int i=0;i<data.length();i++)
			{
				Form temp = new Form(data.optJSONObject(i)); 
				forms[i]=temp;
			}
			
			if(data.length()==0)
			{

				menu.toggle();
				Form formEmp[] = new Form[]
						{
						new Form(1, 0, 0, "",
								"", "", "",
								"", "", "","",
								"", "",
								"",
								"",
								"",
								"", "",
			        			"Creado", "", 0,
			        			0,
			        			0,
			        			"",
			        			"",
			        			"",false,"false")
			        };
				ListAdapter adpLis= new ListAdapter(MenuActivity.this, R.layout.listview_item_row, formEmp); 
				listaFormularios.setAdapter(adpLis);
			}
			else
			{			
				menu.toggle();
				ListAdapter adpLis= new ListAdapter(MenuActivity.this, R.layout.listview_item_row, forms); 
				listaFormularios.setAdapter(adpLis);
			}
			
			
		}
	};
    

    private void logicUIEstadistica()
    {
    	this.runOnUiThread(new Runnable() {
    		@Override
    		public void run() {

    			MenuActivity.this.setContentView(R.layout.estadisticas);
    			prefs = PreferenceManager
    					.getDefaultSharedPreferences(getApplicationContext());
    			
    			date1 = (Button) MenuActivity.this.findViewById(R.id.startDate);
    			date2 = (Button) MenuActivity.this.findViewById(R.id.endDate);
    			date3 = (Button) MenuActivity.this.findViewById(R.id.date);
    			
    			//pieChartKey = (TextView) MenuActivity.this.findViewById(R.id.pieChartKey);
    			//pieChartKey2 = (TextView) MenuActivity.this.findViewById(R.id.pieChartKey2);
    			//pieChartKey3 = (TextView) MenuActivity.this.findViewById(R.id.pieChartKey3);
    			//pieChartKey4 = (TextView) MenuActivity.this.findViewById(R.id.pieChartKey4);
    			//pieChartKey5 = (TextView) MenuActivity.this.findViewById(R.id.pieChartKey5);
    			//pieChartKey6 = (TextView) MenuActivity.this.findViewById(R.id.pieChartKey6);
    			filter1 = (Button) MenuActivity.this.findViewById(R.id.filter1);
    			filter2 = (Button) MenuActivity.this.findViewById(R.id.filter2);
    			filter1.setOnClickListener(new OnClickListener() {
    				@Override
    				public void onClick(View v) {
    					if (date1.getText().toString().equalsIgnoreCase("")
    							|| date2.getText().toString().equalsIgnoreCase(""))
    					{
    						Toast.makeText(getApplicationContext(),
    								"Las dos fechas son obligatorias", Toast.LENGTH_LONG).show();
    					}
    					else
    					{
	    					String d1 = date1.getText().toString();
	    					String d2 = date2.getText().toString();
	    					
	    					Log.i("Estadisticas",d1+" "+d2);
	    					
	    					JSONObject request = new JSONObject();
	    					try {
	    						request.put("function", "getStatiscsByDate");
	    						request.put("mobile_key", "");
	    						request.put("resource", "");
	    						request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
	    						request.put("ts_start", d1);
	    						request.put("ts_end", d2);
	    						Log.d("request", request.toString());
	    						
	    						modo="filtroDias";
	    						pd = new ProgressDialog(MenuActivity.this);
					    		pd.setCancelable(false);
								pd.setMessage("Enviando información, por favor espere un momento!!!");
								pd.show();
								ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
					    		executor.execute(request);
	    					} catch (JSONException e) {
	    						Toast.makeText(getApplicationContext(),
	    								"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
	    						e.printStackTrace();
	    					}
    					}
    				}
    			});
    			filter2.setOnClickListener(new OnClickListener() {
    				@Override
    				public void onClick(View v) {
    					String d3 = date3.getText().toString();
    					if (date3.getText().toString().equalsIgnoreCase(""))
    					{
    						Toast.makeText(getApplicationContext(),
    								"La fecha es obligatoria", Toast.LENGTH_LONG).show();
    					}
    					else
    					{
	    					d3 = date3.getText().toString();
	    					Log.i("Estadisticas",d3);
	    					
	    					JSONObject request = new JSONObject();
	    					try {
	    						request.put("function", "getStatiscsByHour");
	    						request.put("mobile_key", "");
	    						request.put("resource", "");
	    						request.put("user", Integer.parseInt(prefs.getString("idUsuario", "")));
	    						request.put("ts_start", d3);
	    						request.put("ts_end", d3);
	    						Log.d("request", request.toString());
	    						
	    						modo="filtroHoras";
	    						pd = new ProgressDialog(MenuActivity.this);
					    		pd.setCancelable(false);
								pd.setMessage("Enviando información, por favor espere un momento!!!");
								pd.show();
								ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
					    		executor.execute(request);
	    					} catch (JSONException e) {
	    						Toast.makeText(getApplicationContext(),
	    								"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
	    						e.printStackTrace();
	    					}
    					}
    					
    				}
    			});

    		
    			ImageView menuForm= (ImageView)MenuActivity.this.findViewById(R.id.ImageView01Est);
				menuForm.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						
						if(isBack==true)
        				{

							isBack=false;
        					MenuActivity.this.setContentView(R.layout.activity_menu);

        					MapButton = (Button) MenuActivity.this.findViewById(R.id.menu_btn_map);
        					MapButton.setOnClickListener(MenuActivity.this);


        					importButton = (Button) MenuActivity.this.findViewById(R.id.menu_btn_video);
        					importButton.setOnClickListener(MenuActivity.this);
        					importButton.setText(resultCount);
							importButton.setTextSize(12);


        					googleMapButton = (Button) MenuActivity.this.findViewById(R.id.Button01);
        					googleMapButton.setOnClickListener(MenuActivity.this);


        					bla = (ImageView) MenuActivity.this.findViewById(R.id.imageView2);
        					bla.setOnClickListener(MenuActivity.this);

        					tareasButton = (Button) MenuActivity.this.findViewById(R.id.Button02);
        					tareasButton.setOnClickListener(MenuActivity.this);
        					
        					ButtonList = (Button) MenuActivity.this.findViewById(R.id.Button03);
							ButtonList.setOnClickListener(MenuActivity.this);
							
							tareasButtonGuarda = (Button) findViewById(R.id.ButtonGuarda);
							//tareasButtonGuarda.setOnClickListener(this);
							tareasButtonGuarda.setVisibility(View.INVISIBLE);

        				}
					}
				});
				
				// sliding
				menu = new SlidingMenu(MenuActivity.this);
				menu.setMode(SlidingMenu.LEFT);
				menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
				menu.setShadowWidthRes(R.dimen.shadow_width);
				menu.setShadowDrawable(R.drawable.shadowslidemenu);
				menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
				menu.setFadeEnabled(true);
				menu.setFadeDegree(0.35f);
				menu.setBackgroundResource(android.R.color.white);
				menu.attachToActivity(MenuActivity.this, SlidingMenu.SLIDING_CONTENT);
				menu.setOnClosedListener(new OnClosedListener() {

					@Override
					public void onClosed() {
						mostrarMenuPrincipal(null);
					}
				});
    			
    			date1.setOnClickListener(new OnClickListener() {
        			@SuppressWarnings("deprecation")
					@Override
        			public void onClick(View v) {
        				showDialog(DATE_1_ID);
        			}
        		});
        		date2.setOnClickListener(new OnClickListener() {
        			@SuppressWarnings("deprecation")
					@Override
        			public void onClick(View v) {
        				showDialog(DATE_2_ID);
        			}
        		});
        		date3.setOnClickListener(new OnClickListener() {
        			@SuppressWarnings("deprecation")
					@Override
        			public void onClick(View v) {
        				showDialog(DATE_3_ID);
        			}
        		});
        		
        		//estPlace = (EditText) findViewById(R.id.buscarEst);
        		//final ImageView logoEst= (ImageView)MenuActivity.this.findViewById(R.id.imageView2Est);
        		/*final Button search = (Button)  MenuActivity.this.findViewById(R.id.Button01infEst);
            	search.setOnClickListener(new OnClickListener() {

        			@Override
        			public void onClick(View v) {
        				if (search.isFocused())
        					logoEst.setVisibility(View.GONE);
        				else if (estPlace.getText().toString().equalsIgnoreCase(""))
        					logoEst.setVisibility(View.VISIBLE);
        				
        			}
        		});*/
        		
            	/*
            	estPlace.setOnFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						if (estPlace.isFocused())
							logoEst.setVisibility(View.GONE);
						else if (estPlace.getText().toString().equalsIgnoreCase(""))
							logoEst.setVisibility(View.VISIBLE);
					}
				});*/
            	
            	Button back=(Button)MenuActivity.this.findViewById(R.id.ButtonAtrasEst);
        		back.setOnClickListener(new OnClickListener() {

        			@Override
        			public void onClick(View v) {
        				

        			}
        		});
    		}
    			
    	});

    }    

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.menu_btn_map:
			isBack=true;
			    callFormulario();
		        if (android.os.Build.VERSION.SDK_INT  > 4) {
		            ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.LEFT);
		        }
			break;
		case R.id.menu_btn_video:
			    /* if (android.os.Build.VERSION.SDK_INT  > 4) {
			            ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.LEFT);
			     }*/
			break;
			
		case R.id.Button01:
			//isBack=true;
			Intent localintent = new Intent(MenuActivity.this,
					MapaActivity.class);
			MenuActivity.this.startActivityForResult(localintent, 124);
			
			//if (android.os.Build.VERSION.SDK_INT  > 4) {
			//	ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.LEFT);
			//}
			break;
			
		case R.id.Button02:
			isBack=true;
			callFormularioEstadisticas();
			if (android.os.Build.VERSION.SDK_INT  > 4) {
				ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.LEFT);
			}
		break; 
		
		case R.id.Button03:
			VariablesdeSesion.getInstance().setCerrarVista(true);
			isBack=true;
			isListForm=true;
			callListaFormularios();
			if (android.os.Build.VERSION.SDK_INT  > 4) {
				ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.LEFT);
			}
		break;
		
		case R.id.ButtonGuarda:
			isBack=true;
			callGuarda();
			if (android.os.Build.VERSION.SDK_INT  > 4) {
				ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.LEFT);
			}
		break;
		
		
		default:
			break;
		}
		
	}
	
	// convert from bitmap to byte array
		public byte[] getBytesFromBitmap(Bitmap bitmap) {
			byte[] res=null;
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.JPEG, 70, stream);
			res= stream.toByteArray();
			return res;
		}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		System.out.println("onActivityResult: " + requestCode + " "
				+ resultCode + " " + data);
		try
		{
			if (requestCode == 124) {
				
			}			
			if (requestCode == CAMERA_REQUEST_CUATRO && resultCode == RESULT_OK) {
				photo1 = (Bitmap) data.getExtras().get("data");
				
			}
			if (requestCode == CAMERA_REQUEST_CINCO && resultCode == RESULT_OK) {
				photo2 = (Bitmap) data.getExtras().get("data");
				
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
	}
	
	private void callFormulario()
	{
		modo="crear";
		logicUI();
	}
	
	private void callListaFormularios()
	{
		modo="consultaFormularios";
		logicUIListaFormularios();
	}
	
	private void callGuarda()
	{
		logicUIGuarda();
	}
	
	private void callFormularioEstadisticas()
	{
		logicUIEstadistica();
	}
	

	@Override
    public boolean onOptionsItemSelected(MenuItem item)
    {    
         return MenuChoice(item);    
    }
	
	private boolean MenuChoice(MenuItem item)
    {        
        switch (item.getItemId()) {
        case OPTION_MENU_BACK:{
            
            return true;
        }
        case OPTION_MENU_EXIT:{
        	 
        	final AlertDialog.Builder adb = new AlertDialog.Builder(this);
            adb.setMessage("Seguro que quiere terminar su sesion?");
            adb.setCancelable(false);
            adb.setPositiveButton("Si", new DialogInterface.OnClickListener() { //Boton Positivo 
                
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                     Toast.makeText(getApplicationContext(), "Sesion terminada!!!! ", Toast.LENGTH_LONG).show();
                     Intent i = new Intent(MenuActivity.this, MainActivity.class);
                     i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                     //count.cancel();
        			 startActivity(i); 
        			
        		        if (mCaller == CALLER_CARDEDITOR_INTENT_ADD || mCaller == CALLER_BIGWIDGET_EDIT
        		                || mCaller == CALLER_BIGWIDGET_ADD) {
        		            if (android.os.Build.VERSION.SDK_INT  > 4) {
        		                ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.FADE);
        		            }
        		        } else if (mCaller == CALLER_INDICLASH) {
        		            if (android.os.Build.VERSION.SDK_INT  > 4) {
        		                ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.NONE);
        		            }
        		        } else {
        		            if (android.os.Build.VERSION.SDK_INT  > 4) {
        		                ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.RIGHT);
        		            }
        		        }
                }
            });
            
            adb.setNegativeButton("No", new DialogInterface.OnClickListener() {//Boton negativo
                
                public void onClick(DialogInterface dialog, int which) {
                    
                	
                    
                }
            });
            
            adb.show();//Se muestra el AlertDialog
            
            return true;
        }
        default:
        	return false;
        }
    }
	
	    @SuppressWarnings("resource")
		public static byte[] getBytesFromFile(File file) throws IOException {
	    	
	        InputStream is = new FileInputStream(file);
	        // Get the size of the file
	        long length = file.length();
	        // You cannot create an array using a long type.
	        // It needs to be an int type.
	        // Before converting to an int type, check
	        // to ensure that file is not larger than Integer.MAX_VALUE.
	        if (length > Integer.MAX_VALUE) {
	            // File is too large
	        }

	        // Create the byte array to hold the data
	        byte[] bytes = new byte[(int)length];

	        // Read in the bytes
	        int offset = 0;
	        int numRead = 0;
	        while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
	            offset += numRead;
	        }

	        // Ensure all the bytes have been read in
	        if (offset < bytes.length) {
	            throw new IOException("Could not completely read file "+file.getName());
	        }

	        // Close the input stream and return bytes
	        is.close();
	        return bytes;
	    }
	   
	    
	   
	    
	    private void ejecutar()
	    {
	        
	        timerSync.scheduleAtFixedRate(new TimerTask() {
	            @Override
	            public void run() {
	            	JSONObject encuesta=new JSONObject();
	            	try {
						encuesta.put("function", "sincronizar");
						sincronizar(encuesta);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	                
	            }
	        }, 0, syncTask);
	        
	        
	    }
	    
	    private void sincronizar(JSONObject encuesta)
	    {
	    	ManagerExecutor executor = new ManagerExecutor(MenuActivity.this, MenuActivity.this.getBaseContext());
    		executor.execute(encuesta);
	    }
	    
	    
	   private void actualizarPosicion()
	    {
		   try
		   {
			   //Obtenemos una referencia al LocationManager
			   locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

			   //Obtenemos la �ltima posici�n conocida
			   Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			   //Mostramos la �ltima posici�n conocida
			   muestraPosicion(location);

			   //Nos registramos para recibir actualizaciones de la posici�n
			   locationListener = new LocationListener() {
				   public void onLocationChanged(Location location) {
					   muestraPosicion(location);
				   }
				   public void onProviderDisabled(String provider){
					   Log.i(TAG,"Provider OFF");
				   }
				   public void onProviderEnabled(String provider){
					   Log.i(TAG,"Provider ON");
				   }
				   public void onStatusChanged(String provider, int status, Bundle extras){
					   Log.i("LocAndroid", "Provider Status: " + status);
					   Log.i(TAG,"Provider Status: " + status);
				   }
			   };

			   locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0, locationListener);
		   }
		   catch(Exception ex)
		   {
			   ex.printStackTrace();

		   }
	    }
	   
	    private void muestraPosicion(Location loc) {
	    	
	    	if(loc != null)
	    	{
	    		lastlocation=new Location(loc);
	    		latitud=String.valueOf(loc.getLatitude());
	    		longitud=String.valueOf(loc.getLongitude());
	    		
	    		Log.e("POCISION :", latitud+" y ademas "+longitud);
	    		latitud="";
	    		longitud="";
	
	    	
	    	}
	    }
	    
	    @SuppressWarnings("unused")
		private void close() {
	        close(null);
	    }
	    
	    private void close(Intent intent) {
	        int result;
	        if (mChanged) {
	            result = RESULT_OK;
	        } else {
	            result = RESULT_CANCELED;
	        }
	        close(result, intent);
	    }
	    
	    private void close(int result, Intent intent) {
	        if (intent != null) {
	            setResult(result, intent);
	        } else {
	            setResult(result);
	        }
	        finish();
	        if (mCaller == CALLER_CARDEDITOR_INTENT_ADD || mCaller == CALLER_BIGWIDGET_EDIT
	                || mCaller == CALLER_BIGWIDGET_ADD) {
	            if (android.os.Build.VERSION.SDK_INT  > 4) {
	                ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.FADE);
	            }
	        } else if (mCaller == CALLER_INDICLASH) {
	            if (android.os.Build.VERSION.SDK_INT  > 4) {
	                ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.NONE);
	            }
	        } else {
	            if (android.os.Build.VERSION.SDK_INT  > 4) {
	                ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.RIGHT);
	            }
	        }
	    }
	
	    private void limpiarForm()
	    {
	    	nombre.setText("");
			apellido.setText("");
			documento.setText("");
			numeroTelefonico2.setText("");
			numeroCelular1.setText("");
			mensajeProximoContacto.setText("");
			observaciones.setText("");
			fechaderegistro.setText("");;
			numeroCelular2.setText("");
			numeroTelefonico1.setText("");
			operadorActualdeTelevision.setSelection(0);
			Cobertura.setSelection(0);
			ProductoInteres.setSelection(0);
			
			
			tipodeContactoaRealizar.setSelection(0);;
			estadoR="CREADO";
			contactoaRealizarR="";
			strings5 = new ArrayList<String>();
			strings5.add("CREADO");// si esta creado no vuelve
			Estado.setAdapter(new ArrayAdapter<String>(
					getApplicationContext(), R.layout.spinner_item, strings5));
			Estado.setSelection(0);
			tipoDocumento.setSelection(0);
			operadorR="";
			cal=null;
			year=0;
			month=0;
			day=0;
			hour=0;
			minute=0;
			//buscar.setText("");
			
			date = "";
			datePicker.setText("Seleccionar Fecha");
			
			hour = 0;
			minute = 0;
			hourFinal = new StringBuilder();
			result="";
			mBitmap=null;
	
			correo.setText("");
			direccion.setText("");
			timePicker.setText("Seleccionar hora");
			modo="crear";
			acepto.setChecked(false);
			habilitarUI();
	    }
	    
	    private void fillForm(Form form)
	    {
	    	this.form=form;
	    	estadoR="CREADO";
			contactoaRealizarR="";
			operadorR="";
			productointeresR="";
			coberturaR="";
			
	    	
	    	if(isListForm)
	    	{
	    		isListForm=false;
	    		logicUI();
	    	}
	    	
			
			operadorActualdeTelevision.setSelection(0);
			tipodeContactoaRealizar.setSelection(0);
			tipoDocumento.setSelection(0);	    	
			Cobertura.setSelection(0);
			ProductoInteres.setSelection(0);
	    	
	    	int cont1=0,cont2=0,cont4=0,cont5=0,cont6=0,cont7=0;
	    	
	    	if(form.getEstado().trim().equalsIgnoreCase("creado"))
	    	{
	    		strings5 = new ArrayList<String>();
	    		strings5.add("CREADO");// si esta creado no vuelve
	    		strings5.add("CONTACTO 1");// no se devuelve a creado
	    		strings5.add("CONTACTO 2");//no se devuelve a los anteriores
	    		strings5.add("CONTACTO 3");//no se devuelve a los anteriores
	    		strings5.add("VENTA");// no es editable
	    		strings5.add("DECLINADO");//no es editable
	    		habilitarUI();
	    	}
	    	else
	    	{
	    		if(form.getEstado().trim().equalsIgnoreCase("contacto 1"))
		    	{
		    		strings5 = new ArrayList<String>();
		    		strings5.add("CONTACTO 1");// no se devuelve a creado
		    		strings5.add("CONTACTO 2");//no se devuelve a los anteriores
		    		strings5.add("CONTACTO 3");//no se devuelve a los anteriores
		    		strings5.add("VENTA");// no es editable
		    		strings5.add("DECLINADO");//no es editable
		    		habilitarUI();
		    	}
	    		else
	    		{
	    			if(form.getEstado().trim().equalsIgnoreCase("contacto 2"))
			    	{
			    		strings5 = new ArrayList<String>();
			    		strings5.add("CONTACTO 2");//no se devuelve a los anteriores
			    		strings5.add("CONTACTO 3");//no se devuelve a los anteriores
			    		strings5.add("VENTA");// no es editable
			    		strings5.add("DECLINADO");//no es editable
			    		habilitarUI();
			    	}
	    			else
	    			{
	    				if(form.getEstado().trim().equalsIgnoreCase("contacto 3"))
	    		    	{
	    		    		strings5 = new ArrayList<String>();
	    		    		strings5.add("CONTACTO 3");//no se devuelve a los anteriores
	    		    		strings5.add("VENTA");// no es editable
	    		    		strings5.add("DECLINADO");//no es editable
	    		    		habilitarUI();
	    		    	}
	    				else
	    				{
	    					if(form.getEstado().trim().equalsIgnoreCase("venta"))
	    			    	{
	    			    		strings5 = new ArrayList<String>();
	    			    		strings5.add("VENTA");// no es editable
	    			    		strings5.add("DECLINADO");//no es editable
	    			    		
	    			    		//INHABILITAR UI
	    			    		inhabilitarUI();
	    			    	}
	    					else
	    					{
	    						if(form.getEstado().trim().equalsIgnoreCase("declinado"))
		    			    	{
		    			    		strings5 = new ArrayList<String>();
		    			    		strings5.add("DECLINADO");//no es editable
		    			    		
		    			    		//INHABILITAR UI
		    			    		inhabilitarUI();
		    			    	}
	    					}
	    				}
	    			}
	    		}
	    	}
	    	
	    	for(String str:strings5)
	    	{
	    		if(!str.trim().equalsIgnoreCase(form.getEstado().trim()))
	    		{
	    			cont2++;
	    		}
	    		else
	    		{
	    			break;
	    		}
	    	}
	    	
	    	
	    	
	    	cont4=strings4.indexOf(form.getTipo_documento());
	    	cont1=strings.indexOf(form.getOperador_actual_de_television());
	    	cont2=strings2.indexOf(form.getTipo_de_contacto_a_realizar());
	    	cont5=strings5.indexOf(form.getEstado());
	    	
	    	if(form.getCovertura().trim().equals("true"))
	    	{
	    		cont6=strings6.indexOf("Si");	
	    	}
	    	else
	    		cont6=strings6.indexOf("No");
	    		
	    	cont7=strings7.indexOf(form.getProducto_interes());
	    	
	    	if(cont4 < 0)
	    		cont4 = 0;
	    	
	    	if(cont1 < 0)
	    		cont1 = 0;
	    	
	    	if(cont2 < 0)
	    		cont2 = 0;
	    	
	    	if(cont5 < 0)
	    		cont5 = 0;
	    	
	    	nombre.setText(form.getNombre());
			apellido.setText(form.getApellido());
			documento.setText(form.getDocumento());
			numeroTelefonico2.setText(form.getNumero_telefonico_2());
			numeroCelular1.setText(form.getNumero_celular_1());
			mensajeProximoContacto.setText(form.getMensaje_proximo_contacto());
			observaciones.setText(form.getObservaciones());
			fechaderegistro.setText(form.getFecha_de_registro());;
			numeroCelular2.setText(form.getNumero_celular_2());
			numeroTelefonico1.setText(form.getNumero_telefonico_1());
			operadorActualdeTelevision.setSelection(cont1);
			Cobertura.setSelection(cont6);
			ProductoInteres.setSelection(cont7);
			tipodeContactoaRealizar.setSelection(cont2);
			Estado.setAdapter(new ArrayAdapter<String>(
					getApplicationContext(), R.layout.spinner_item, strings5));
			tipoDocumento.setSelection(cont4);
			Estado.setSelection(cont5);
			String[] fecha=form.getFecha_y_hora_proximo_contacto().split(" ");
			date=fecha[0];
			datePicker.setText(fecha[0]);
			hourFinal=new StringBuilder(fecha[1]);
			timePicker.setText(hourFinal);
			estadoR=form.getEstado();
			correo.setText(form.getEmail());
			direccion.setText(form.getDireccion());
			
			if(form.getAcepta().equals("true") || form.getAcepta().equals("t"))
			{
				acepto.setChecked(true);
				
			}
			else
			{
				acepto.setChecked(false);
			}
	    }
	    
	    private void inhabilitarUI()
	    {
	    	nombre.setEnabled(false);
			apellido.setEnabled(false);
			documento.setEnabled(false);
			numeroTelefonico2.setEnabled(false);
			numeroCelular1.setEnabled(false);
			mensajeProximoContacto.setEnabled(false);
			observaciones.setEnabled(false);
			fechaderegistro.setEnabled(false);
			numeroCelular2.setEnabled(false);
			numeroTelefonico1.setEnabled(false);
			operadorActualdeTelevision.setEnabled(false);
			tipodeContactoaRealizar.setEnabled(false);
			
			Estado.setEnabled(false);
			tipoDocumento.setEnabled(false);
			//buscar.setText("");
			datePicker.setEnabled(false);
			correo.setEnabled(false);
			direccion.setEnabled(false);
			acepto.setEnabled(false);
			timePicker.setEnabled(false);
			Button sub =(Button) findViewById(R.id.submit);
			sub.setVisibility(View.GONE);
			

			sub =(Button) findViewById(R.id.ButtonFimar);
			sub.setVisibility(View.GONE);
	    }
	    
	    private void habilitarUI()
	    {
	    	nombre.setEnabled(true);
			apellido.setEnabled(true);
			documento.setEnabled(true);
			numeroTelefonico2.setEnabled(true);
			numeroCelular1.setEnabled(true);
			mensajeProximoContacto.setEnabled(true);
			observaciones.setEnabled(true);
			fechaderegistro.setEnabled(true);
			lblAvisoLegal.setEnabled(true);
			numeroCelular2.setEnabled(true);
			numeroTelefonico1.setEnabled(true);
			operadorActualdeTelevision.setEnabled(true);
			tipodeContactoaRealizar.setEnabled(true);
			
			Estado.setEnabled(true);
			tipoDocumento.setEnabled(true);
			//buscar.setText("");
			datePicker.setEnabled(true);
			correo.setEnabled(true);
			direccion.setEnabled(true);
			acepto.setEnabled(true);
			timePicker.setEnabled(true);
			Button sub =(Button) findViewById(R.id.submit);
			sub.setVisibility(View.VISIBLE);
			
			sub =(Button) findViewById(R.id.ButtonFimar);
			sub.setVisibility(View.VISIBLE);
	    }


		@Override
		public void procesarRespuesta(JSONObject json) {
			
			try
			{
				if(modo.trim().equalsIgnoreCase("crear"))
				{

					String result;
					try {
						result = json.getString("error");
						if(result.trim().equalsIgnoreCase("false"))
						{

							limpiarForm();
							if (pd != null && pd.isShowing()) {
								pd.dismiss();
							}
							Toast.makeText(getApplicationContext(),
									"Información almacenada de manera exitosa!!!", Toast.LENGTH_SHORT)
									.show();
							form=new Form();
							limpiarForm();
							pd.dismiss();
							
						}
						else
						{
							if (pd != null && pd.isShowing()) {
								pd.dismiss();
							}
							Toast.makeText(getApplicationContext(),
									"Ha ocurrido un error al enviar la información. Motivo del fallo: "+json.getString("msg"), Toast.LENGTH_SHORT)
									.show();

						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						dismisspd();
					}

					Log.e("Resulatdo crear", json.toString());
				}
				else if(modo.trim().equalsIgnoreCase("filtroDias"))
				{

					if (pd != null && pd.isShowing()) {
						pd.dismiss();
					}
					String result;
					try {
						result = json.optString("error");

						Log.i("Libreria",json.toString()+" "+result);
											
						if(result.trim().equalsIgnoreCase("false"))
						{
							JSONArray datos1=json.optJSONArray("data1");
							
							perDay = (BarGraph) findViewById(R.id.perDay);
							perDay.setClickable(false);
							ArrayList<Bar> points = new ArrayList<Bar>();
							int total=datos1.length();
							if(total>7)
								total=7;
							for (int i = 0; i <datos1.length(); i++) {
								Bar d = new Bar();
								d.setValue(datos1.optJSONObject(i).getInt("value"));
								d.setName(datos1.optJSONObject(i).getString("date"));
								if(i%2==0)
								{
									d.setColor(Color.parseColor("#eabc1f"));
								}
								else
								{
									d.setColor(Color.parseColor("#d61f26"));
								}
								points.add(d);
							}
							perDay.setBars(points);
							perDay.setUnit(" ");
							
							JSONArray datos2=json.optJSONArray("data2");
							
							int contactos=datos2.optJSONObject(0).optInt("contact1")+datos2.optJSONObject(0).optInt("contact2")+datos2.optJSONObject(0).optInt("contact3");
							int creados=datos2.optJSONObject(0).optInt("created");
							int declinados=datos2.optJSONObject(0).optInt("declined");
							int venta=datos2.optJSONObject(0).optInt("sell");
							
							PieGraph pg = (PieGraph)findViewById(R.id.status);
							pg.removeSlices();
							PieSlice slice = new PieSlice();
							slice.setColor(Color.parseColor("#eabc1f"));
							slice.setValue(contactos);
							pg.addSlice(slice);
							slice = new PieSlice();
							slice.setColor(Color.parseColor("#d61f26"));
							slice.setValue(creados);
							pg.addSlice(slice);
							slice = new PieSlice();
							slice.setColor(Color.parseColor("#463d98"));
							slice.setValue(declinados);
							pg.addSlice(slice);
							slice = new PieSlice();
							slice.setColor(Color.parseColor("#888888"));
							slice.setValue(venta);
							pg.addSlice(slice);
							TextView legend = (TextView) MenuActivity.this.findViewById(R.id.textLegend);
							
							Spannable wordtoSpan = new SpannableString("Creados:"+creados+"\nContacto:"+contactos+"\nVenta:"+venta+"\nDeclinado:"+declinados);        
							int pos=0;
							wordtoSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#d61f26")), pos, (pos+("Creados:"+creados).length()), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
							pos=pos+("Creados:"+creados).length()+1;
							wordtoSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#eabc1f")), pos,  (pos+("Contacto:"+contactos).length()), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
							pos=pos+("Contacto:"+contactos).length()+1;
							wordtoSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#888888")), pos,  (pos+("Venta:"+venta).length()), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
							pos=pos+("Venta:"+venta).length()+1;
							wordtoSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#463d98")), pos,  (pos+("Declinado:"+declinados).length()), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
							legend.setText(wordtoSpan);
							
						}
						else
						{
							Toast.makeText(getApplicationContext(),
									"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
						}
						
					}
					catch (Exception e)
					{
						Toast.makeText(getApplicationContext(),
								"Ocurrio un error en el servicio.", Toast.LENGTH_LONG).show();
						dismisspd();
					}
				}
				else if(modo.trim().equalsIgnoreCase("filtroHoras"))
				{

					if (pd != null && pd.isShowing()) {
						pd.dismiss();
					}
					String result;
					try {
						result = json.optString("error");

						Log.i("Libreria",json.toString()+" "+result);
											
						if(result.trim().equalsIgnoreCase("false"))
						{
							JSONArray datos1=json.optJSONArray("data");
							
							perHour = (BarGraph) findViewById(R.id.perHour);
							perHour.setClickable(false);
							ArrayList<Bar> points = new ArrayList<Bar>();
							for (int i = 0; i <8; i++) {//datos1.length(); i++) {
								Bar d = new Bar();
								d.setValue(datos1.optJSONObject(i).optInt("value"));
								d.setName(datos1.optJSONObject(i).optString("hour"));
								if(i%2==0)
								{
									d.setColor(Color.parseColor("#eabc1f"));
								}
								else
								{
									d.setColor(Color.parseColor("#d61f26"));
								}
								points.add(d);
							}
							perHour.setBars(points);
							perHour.setUnit(" ");
							
						}
						else
						{
							Toast.makeText(getApplicationContext(),
									"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
						}
						
					}
					catch (Exception e)
					{
						Toast.makeText(getApplicationContext(),
								"Ocurrio un error en el servicio.", Toast.LENGTH_LONG).show();
						dismisspd();
					}
				}
				else if(modo.trim().equalsIgnoreCase("consultaFormularios"))
				{

					if (pd != null && pd.isShowing()) {
						
							pd.dismiss();
							VariablesdeSesion.getInstance().setCerrarVista(false);
							
							
					}
					String result;
					try {
						result = json.optString("error");
						
						if(result.trim().equalsIgnoreCase("false"))
						{
							JSONArray datos1=json.optJSONArray("data");
							Totalpage=(int) Math.ceil((double)json.optInt("total")/(double)5);
							Log.i("TOTAL SERVICIO ",""+json.optInt("total"));
							Log.i("TOTAL PAGINAS ",""+Totalpage);
							Form respuestas[]= new Form[datos1.length()];
							for (int i = 0; i < datos1.length(); i++) {
								JSONObject aux;
								Form temp = new Form();
								try {
									aux = datos1.getJSONObject(i);
									temp = new Form(aux);
								} catch (JSONException e) {
									e.printStackTrace();
								}			
								respuestas[i] = temp;
							}
							Log.i("Libreria",respuestas[0].getApellido());
							
							/*
							final ListView listView = (ListView) findViewById(R.id.lvMenuProspectos);
						    adapter = new ListAdapter(MenuActivity.this,R.layout.listview_item_row, respuestas);
						    listView.setAdapter(adapter);*/
						    
						    //ListAdapter adpLis= new ListAdapter(MenuActivity.this, R.layout.listview_item_row, respuestas); 
							adapter =new ListAdapter(MenuActivity.this, R.layout.listview_item_row, respuestas); 
							
							listaFormularios.setAdapter(adapter);

						
						}
						else
						{
							Toast.makeText(getApplicationContext(),
									"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
						}

					}
					catch (Exception e)
					{
						dismisspd();
					}
				}
				else if(modo.trim().equalsIgnoreCase("consultanombres"))
				{
					
					JSONArray data=json.optJSONArray("data");
					
					
					if(data.length()>0){
						Form[] forms =new Form[data.length()];

						for(int i=0;i<data.length();i++)
						{
							Form temp = new Form(data.optJSONObject(i)); 
							forms[i]=temp;
						}    						

						VariablesdeSesion.getInstance().setTotalFormularios(data.length());		
							listaFormularios.setVisibility(View.VISIBLE);					
							
							ListAdapter adpLis= new ListAdapter(MenuActivity.this, R.layout.listview_item_row, forms); 
							listaFormularios.setAdapter(adpLis);
						
					}else{
						Form formEmp[] = new Form[]
								{
								new Form(1, 0, 0, "",
										"", "", "",
										"", "", "","",
										"", "",
										"",
										"",
										"",
										"", "",
					        			"Creado", "", 0,
					        			0,
					        			0,
					        			"",
					        			"",
					        			"",false,"false")
					        };
						ListAdapter adpLis= new ListAdapter(MenuActivity.this, R.layout.listview_item_row, formEmp); 
						listaFormularios.setAdapter(adpLis);
						
					}
		
				}
				else
				{

					if(modo.trim().equalsIgnoreCase("editando"))
					{
						String result2;
						try {
							result2 = json.getString("error");
							if(result2.trim().equalsIgnoreCase("false"))
							{
								if (pd != null && pd.isShowing()) {
									pd.dismiss();
								}
								Toast.makeText(getApplicationContext(),
										"Información actualizada de manera exitosa!!!", Toast.LENGTH_SHORT)
										.show();
								limpiarForm();
								form=new Form();

							}
							else
							{
								if (pd != null && pd.isShowing()) {
									pd.dismiss();
								}
								Toast.makeText(getApplicationContext(),
										"Ha ocurrido un error al enviar la información. Motivo del fallo: "+json.getString("msg"), Toast.LENGTH_SHORT)
										.show();
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							dismisspd();
						}
					}


				}
				
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
				dismisspd();

			}
			try {
				if(json!=null)
				{
					
					resultCount="Formularios sin enviar: "+"\n"+json.getJSONArray("data").getJSONObject(0).optInt("total");
					
					int total = json.getJSONArray("data").getJSONObject(0).optInt("total");
					if(total != 0){
						VariablesdeSesion.getInstance().setContadorFormularios(String.valueOf(total));
					}
					importButton.setText(resultCount);
					importButton.setTextSize(12);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				dismisspd();
			}
			dismisspd();

		}   
		
		public void dismisspd(){
			if (pd != null ) {
				if (pd.isShowing())
				{
				pd.dismiss();
				}
			}
		}
		
		public String encodeTobase64(Bitmap image) {
			Bitmap immagex = image;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			immagex.compress(Bitmap.CompressFormat.PNG, 100, baos);
			byte[] b = baos.toByteArray();
			String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
			return imageEncoded;
		}
		
		 private class AutoCompleteAdapter extends ArrayAdapter<Form> implements Filterable {

		        private LayoutInflater mInflater;
		        private StringBuilder mSb = new StringBuilder();

		        public AutoCompleteAdapter(final Context context) {
		            super(context, -1);
		            mInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
		          
		        }

		        @Override
		        public View getView(final int position, final View convertView, final ViewGroup parent) {
		            final TextView tv;
		            if (convertView != null) {
		                tv = (TextView) convertView;
		            } else {
		                tv = (TextView) mInflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
		            }

		            tv.setText(getItem(position).getDocumento()+" - "+getItem(position).getNombre() + " " + getItem(position).getApellido());
		            return tv;
		        }

		        @Override
		        public Filter getFilter() {
		            Filter myFilter = new Filter() {
		                @Override
		                protected FilterResults performFiltering(final CharSequence constraint) {
		                    List<Form> addressList = null;
		                    if (constraint != null) {
		                        try {
		                            addressList = s.getResultsByString((String) constraint,Integer.parseInt(prefs.getString("idUsuario", "")));
		                        } catch (Exception e) {
		                        }
		                    }
		                    if (addressList == null) {
		                        addressList = new ArrayList<Form>();
		                    }

		                    final FilterResults filterResults = new FilterResults();
		                    filterResults.values = addressList;
		                    filterResults.count = addressList.size();

		                    return filterResults;
		                }

		                @SuppressWarnings("unchecked")
		                @Override
		                protected void publishResults(final CharSequence contraint, final FilterResults results) {
		                    clear();
		                    for (Form address : (List<Form>) results.values) {
		                        add(address);
		                    }
		                    if (results.count > 0) {
		                        notifyDataSetChanged();
		                    } else {
		                        notifyDataSetInvalidated();
		                    }
		                }

		                @Override
		                public CharSequence convertResultToString(final Object resultValue) {
		                	
		                	String resultado = "";
		                	
		                	if(resultValue != null)
		                	{
		                		resultado = ((Form)resultValue).getDocumento()+" - "+((Form)resultValue).getNombre() + " " + ((Form)resultValue).getApellido();
		                	}
		                	
		                    return resultado;
		                }
		            };
		            return myFilter;
		        }
		    }

		 @Override
		 public boolean onKeyDown(int keyCode, KeyEvent event) {

			 if(isBack==false)
			 {
				 if (keyCode == KeyEvent.KEYCODE_BACK) {
					 final AlertDialog.Builder adb = new AlertDialog.Builder(this);
					 adb.setMessage("Seguro que quiere terminar su sesion?");
					 adb.setCancelable(false);
					 adb.setPositiveButton("Si", new DialogInterface.OnClickListener() { //Boton Positivo 

						 public void onClick(DialogInterface dialog, int which) {
							 // TODO Auto-generated method stub
							 Toast.makeText(getApplicationContext(), "Sesion terminada!!!! ", Toast.LENGTH_LONG).show();
							 Intent i = new Intent(MenuActivity.this, MainActivity.class);
							 i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							 //count.cancel();
							 //stopService(new Intent(MenuActivity.this, ServicioAlarama.class));
							 startActivity(i); 

							 if (mCaller == CALLER_CARDEDITOR_INTENT_ADD || mCaller == CALLER_BIGWIDGET_EDIT
									 || mCaller == CALLER_BIGWIDGET_ADD) {
								 if (android.os.Build.VERSION.SDK_INT  > 4) {
									 ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.FADE);
								 }
							 } else if (mCaller == CALLER_INDICLASH) {
								 if (android.os.Build.VERSION.SDK_INT  > 4) {
									 ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.NONE);
								 }
							 } else {
								 if (android.os.Build.VERSION.SDK_INT  > 4) {
									 ActivityTransitionAnimation.slide(MenuActivity.this, ActivityTransitionAnimation.RIGHT);
								 }
							 }
						 }
					 });

					 adb.setNegativeButton("No", new DialogInterface.OnClickListener() {//Boton negativo

						 public void onClick(DialogInterface dialog, int which) {



						 }
					 });

					 adb.show();//Se muestra el AlertDialog
					 return true;
				 }
			 }

			 return super.onKeyDown(keyCode, event);
		 }
		 
		 public class signature extends View 
		 {
			 private static final float STROKE_WIDTH = 5f;
			 private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
			 private Paint paint = new Paint();
			 private Path path = new Path();

			 private float lastTouchX;
			 private float lastTouchY;
			 private final RectF dirtyRect = new RectF();

			 public signature(Context context, AttributeSet attrs) 
			 {
				 super(context, attrs);
				 paint.setAntiAlias(true);
				 paint.setColor(Color.BLACK);
				 paint.setStyle(Paint.Style.STROKE);
				 paint.setStrokeJoin(Paint.Join.ROUND);
				 paint.setStrokeWidth(STROKE_WIDTH);
			 }

			 public void save(View v) 
			 {
				 Log.v("log_tag", "Width: " + v.getWidth());
				 Log.v("log_tag", "Height: " + v.getHeight());
				 if(mBitmap == null)
				 {
					 mBitmap =  Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);;
				 }
				 Canvas canvas = new Canvas(mBitmap);
				 try
				 {
					 //FileOutputStream mFileOutStream = new FileOutputStream(mypath);

					 v.draw(canvas); 
					 // mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream); 
					 //mFileOutStream.flush();
					 //mFileOutStream.close();
					 //url = Images.Media.insertImage(getContentResolver(), mBitmap, "Title", null);
					 result = this.guardarImagen(mBitmap);
					 Log.v("log_tag","url: "+result );
					 //In case you want to delete the file
					 //boolean deleted = mypath.delete();
					 //Log.v("log_tag","deleted: " + mypath.toString() + deleted);
					 //If you want to convert the image to string use base64 converter

				 }
				 catch(Exception e) 
				 { 
					 Log.v("log_tag", e.toString()); 
				 } 
			 }

			 private String  guardarImagen (Bitmap imagen){
				 String res="";
				 /*File path = new File(tempDir, current);

				 FileOutputStream fos = null;
				 try{
					 fos = new FileOutputStream(path);
					 imagen.compress(Bitmap.CompressFormat.PNG, 90, fos);
					 fos.flush();
					 fos.close();
				 }catch (FileNotFoundException ex){
					 ex.printStackTrace();
				 }catch (IOException ex){
					 ex.printStackTrace();
				 }
				 return path.getAbsolutePath();*/
				 foto= getBytesFromBitmap(imagen);
				 if(foto!=null)
					  res= encodeTobase64(imagen);
				 return res;
			 }

			 public void clear() 
			 {
				 path.reset();
				 invalidate();
			 }

			 @Override
			 protected void onDraw(Canvas canvas) 
			 {
				 canvas.drawPath(path, paint);
			 }

			 @Override
			 public boolean onTouchEvent(MotionEvent event) 
			 {
				 float eventX = event.getX();
				 float eventY = event.getY();
				 mGetSign.setEnabled(true);

				 switch (event.getAction()) 
				 {
				 case MotionEvent.ACTION_DOWN:
					 path.moveTo(eventX, eventY);
					 lastTouchX = eventX;
					 lastTouchY = eventY;
					 return true;

				 case MotionEvent.ACTION_MOVE:

				 case MotionEvent.ACTION_UP:

					 resetDirtyRect(eventX, eventY);
					 int historySize = event.getHistorySize();
					 for (int i = 0; i < historySize; i++) 
					 {
						 float historicalX = event.getHistoricalX(i);
						 float historicalY = event.getHistoricalY(i);
						 expandDirtyRect(historicalX, historicalY);
						 path.lineTo(historicalX, historicalY);
					 }
					 path.lineTo(eventX, eventY);
					 break;

				 default:
					 debug("Ignored touch event: " + event.toString());
					 return false;
				 }

				 invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
						 (int) (dirtyRect.top - HALF_STROKE_WIDTH),
						 (int) (dirtyRect.right + HALF_STROKE_WIDTH),
						 (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

				 lastTouchX = eventX;
				 lastTouchY = eventY;

				 return true;
			 }

			 private void debug(String string){
			 }

			 private void expandDirtyRect(float historicalX, float historicalY) 
			 {
				 if (historicalX < dirtyRect.left) 
				 {
					 dirtyRect.left = historicalX;
				 } 
				 else if (historicalX > dirtyRect.right) 
				 {
					 dirtyRect.right = historicalX;
				 }

				 if (historicalY < dirtyRect.top) 
				 {
					 dirtyRect.top = historicalY;
				 } 
				 else if (historicalY > dirtyRect.bottom) 
				 {
					 dirtyRect.bottom = historicalY;
				 }
			 }

			 private void resetDirtyRect(float eventX, float eventY) 
			 {
				 dirtyRect.left = Math.min(lastTouchX, eventX);
				 dirtyRect.right = Math.max(lastTouchX, eventX);
				 dirtyRect.top = Math.min(lastTouchY, eventY);
				 dirtyRect.bottom = Math.max(lastTouchY, eventY);
			 }
		 }
		 
		 // CONFIGURACION DE EVENT
		 private void configurarEvento(Context context, String celular, Date fecha,String nombre,Notificacion noti)
		 {
			 id++;
			 noti.set_id(id);
			 Intent i=new Intent(this,ServicioAlarma.class);
			 i.putExtra("celular", celular);
			 Calendar cal = Calendar.getInstance();
			 cal.setTime(fecha);
			 long startTime = cal.getTimeInMillis();
			 i.putExtra("fecha", startTime);
			 i.putExtra("fechaString", fecha.toLocaleString());
			 i.putExtra("id", String.valueOf(id));
			 i.putExtra("nombre", nombre);
			 Bundle bundle = new Bundle();  
			 bundle.putSerializable("notificacion", (Serializable) noti);
			 i.putExtras(bundle);
			 startService(i);
		 }
		 
		 private Date stringTodate(String data)
		 {
			 Date date=null;
			 SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
			 try {  
			     date = format.parse(data);  
			     System.out.println(date);  
			 } catch (ParseException e) {  
			     // TODO Auto-generated catch block  
			     e.printStackTrace();  
			 }
			 return date;
		 }
}
